123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532 |
- /**
- * 用户业务模型
- *
- * @author CaiAoLin
- * @date 2017/6/9
- * @version
- */
- import mongoose from "mongoose";
- import Request from "request";
- import BaseModel from "../../common/base/base_model"
- import LogModel from "./log_model";
- class UserModel extends BaseModel {
- /**
- * 企业所在地区
- *
- * @var {object}
- */
- province = ['北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏', '浙江', '安徽',
- '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '重庆', '四川', '贵州', '云南', '西藏',
- '陕西', '甘肃', '青海', '宁夏', '新疆', '台湾', '香港', '澳门',];
- /**
- * 企业类型
- *
- * @var
- */
- companyType = ['建设单位', '设计单位', '施工单位', '监理单位', '审核单位', '咨询公司', '招标代理', '住建部', '财政', '审计',
- '造价管理站', '学校', '个人', '其他'];
- /**
- * 企业规模
- *
- * @var
- */
- companyScale = ['1-50', '50-100', '100-500', '500+'];
- /**
- * 最近天数
- *
- * @var
- */
- dayMsg = ['所有', '最近24小时', '最近3天', '最近7天', '最近30天'];
- /**
- * 构造函数
- *
- * @return {void}
- */
- constructor() {
- let parent = super();
- parent.model = mongoose.model('user');
- parent.init();
- }
- /**
- * 根据用户名密码调用SSO接口获取信息
- *
- * @param {string} username
- * @param {string} password
- * @return {object}
- */
- async getInfoFromSSO(username, password) {
- let postData = {
- url: 'http://sso.smartcost.com.cn/api/jzlogin',
- form: {username: username, userpasswd: password},
- encoding: 'utf8'
- };
- return new Promise(function (resolve, reject) {
- try {
- // 请求接口
- Request.post(postData, function (err, postResponse, body) {
- if (err) {
- console.log('111');
- reject('请求错误');
- }
- if (postResponse.statusCode !== 200) {
- reject('通行证验证失败!');
- }
- resolve(body);
- });
- } catch (error) {
- reject([]);
- }
- });
- }
- /**
- * 根据用户手机号码调用SSO接口获取信息
- *
- * @param {string} mobile
- * @param {string} login 1为登录,不存在则是查询
- * @return {object}
- */
- async getInfoFromSSOMobile(mobile, login = '1') {
- const fromData = {account: mobile};
- if (login === '1') {
- fromData.login = 1;
- }
- let postData = {
- url: 'http://sso.smartcost.com.cn/building/api/mobile/login',
- form: fromData,
- encoding: 'utf8'
- };
- return new Promise(function (resolve, reject) {
- try {
- // 请求接口
- Request.post(postData, function (err, postResponse, body) {
- if (err) {
- console.log('111');
- reject('请求错误');
- }
- if(!postResponse) reject('请求错误');
- if (postResponse.statusCode !== 200) {
- reject('通行证验证失败!');
- }
- resolve(body);
- });
- } catch (error) {
- reject([]);
- }
- });
- }
- /**
- * 根据用户id和token调用SSO接口获取信息
- *
- * @param {string} username
- * @param {string} password
- * @return {object}
- */
- async getInfoFromSSO2(ssoID, token) {
- let postData = {
- url: 'http://sso.smartcost.com.cn/building/api/login/auth',
- form: {ssoID: ssoID, token: token},
- encoding: 'utf8'
- };
- return new Promise(function (resolve, reject) {
- try {
- // 请求接口
- Request.post(postData, function (err, postResponse, body) {
- if (err) {
- console.log('111');
- reject('请求错误');
- }
- if (postResponse.statusCode !== 200) {
- reject('通行证验证失败!');
- }
- resolve(body);
- });
- } catch (error) {
- reject([]);
- }
- });
- }
- /**
- * 标记用户
- *
- * @param {object} userData
- * @param {Object} request
- * @return {Promise}
- */
- async markUser(userData, request = null) {
- let userDataFromDb = await this.findDataBySsoId(userData.ssoId);
- // let userDataFromDb = await this.findDataByName(userData.username); //后面新增的账号可淘汰这方法,当前使用是为了兼容旧的账号
- let result = false;
- userData.latest_login = new Date().getTime();
- if (userDataFromDb === null) {
- // 不存在用户则入库
- this.setScene();//恢复场景,用户有可能公司real_name等信息为空,不能设置为必填
- result = await this.addUser(userData);
- userDataFromDb = result;
- } else {
- // 存在则新增登录信息并更新账号信息
- let condition = {ssoId: userData.ssoId};
- // let condition = {username: userData.username};
- let UpdateData = {
- email : userData.email,
- mobile : userData.mobile,
- // ssoId : userData.ssoId,
- qq: userData.qq,
- latest_login:userData.latest_login,
- isUserActive: userData.isUserActive,
- token: userData.token
- };
- console.log("updateUser 开始 -------------------------------");
- let updateResult = await this.updateUser(condition,UpdateData);
- console.log("updateUser 完成 -------------------------------");
- if (updateResult.ok === 1) {
- let logModel = new LogModel();
- result = await logModel.addLoginLog(userDataFromDb._id, request);
- console.log("addLoginLog 完成 -------------------------------");
- }
- }
- request.session.sessionUser.id = userDataFromDb._id;
- request.session.sessionUser.real_name = userDataFromDb.real_name;
- request.session.sessionUser.latest_used = userDataFromDb.latest_used;//设置最近使用的编办
- return result;
- }
- /**
- * 选择场景
- *
- * @param {string} scene
- */
- setScene(scene = '') {
- /* switch (scene) {
- case 'saveInfo':
- this.model.schema.path('real_name').required(true);
- this.model.schema.path('company').required(true);
- this.model.schema.path('province').required(true);
- this.model.schema.path('version').required(true);
- break;
- case '':
- this.model.schema.path('real_name').required(false);
- this.model.schema.path('company').required(false);
- this.model.schema.path('province').required(false);
- this.model.schema.path('version').required(false);
- }*/
- }
- /**
- * 根据用户名查找数据
- *
- * @param {string} username
- * @return {object}
- */
- findDataByName(username) {
- return this.db.findOne({username: username});
- }
- /**
- * 根据ssoID查找数据
- *
- * @param {string} ssoId
- * @return {object}
- */
- findDataBySsoId(ssoId) {
- return this.db.findOne({ssoId: ssoId});
- }
- /**
- * 根据手机号查找数据
- *
- * @param {string} mobile
- * @return {object}
- */
- findDataByMobile(mobile) {
- return this.db.findOne({mobile: mobile});
- }
- /**
- * 根据userId查找数据
- *
- * @param {string} ssoId
- * @return {object}
- */
- async findDataById(id, fields) {
- const objId = mongoose.Types.ObjectId(id);
- return fields ? await this.db.findOne({_id: objId}, fields) : await this.db.findOne({_id: objId});
- }
- /**
- * 验证用户token正确性
- * 一个账号不允许多处同时在线,每次登陆都会更新session和数据库的token,每个请求都会比对session和数据库的token
- * @param {String} id - 用户ID
- * @param {String} token - 登陆生成的token
- * @return {Boolean}
- */
- async checkToken(id, token) {
- const user = await this.findDataById(id, '-_id token');
- if (!user.token) { // 兼容第一次上线,已登陆的用户还没token,需要返回验证正确
- return true;
- }
- return user.token === token;
- }
- async findDataByAccount(account) {
- let userinfo = await this.db.findOne({mobile: account});
- let userinfo2 = await this.db.findOne({email: account});
- if (userinfo) {
- return userinfo;
- } else if (userinfo2) {
- return userinfo2;
- } else {
- return false;
- }
- }
- /**
- * 新增用户
- *
- * @param {object} userData
- * @return {Promise|boolean}
- */
- addUser(userData) {
- let insertData = {
- ssoId: userData.ssoId,
- username: userData.username,
- email: userData.email,
- mobile: userData.mobile,
- qq: userData.qq,
- create_time: new Date().getTime(),
- latest_login: new Date().getTime(),
- isUserActive: userData.isUserActive,
- token: userData.token
- };
- return this.db.create(insertData);
- }
- //更新最近使用编办ID
- async updateLatestUsed(userID,compilationID){
- if(userID && compilationID){
- return await this.db.update({'_id':userID},{'latest_used':compilationID});
- }
- }
- /**
- * 更新用户数据
- *
- * @param {object} updateData
- * @return {Promise}
- */
- async updateUser(condition, updateData) {
- if (Object.keys(condition).length <= 0 || Object.keys(updateData).length <= 0) {
- return null;
- }
- return await this.db.update(condition, updateData);
- }
- async addVersion(condition, versionInfo){
- return await this.db.findOneAndUpdate(condition, {$addToSet: {versionInfo: versionInfo}});
- }
- async removeVersion(userId, compilationId){
- let userObjId = mongoose.Types.ObjectId(userId);
- return await this.db.findOneAndUpdate({_id: userObjId}, {$pull: {versionInfo: {compilationId: compilationId}}});
- }
- /**
- * 判断用户使用免费版还是专业版
- *
- * @param ssoId
- * @param compilationId
- * @return {version}
- */
- async getVersionFromUpgrade(ssoId, compilationId){
- let version = '大司空云计价(免费公用版)';
- let deadline = '';
- let userData = await this.findDataBySsoId(ssoId);
- if (userData.upgrade_list !== undefined) {
- let compilationInfo = userData.upgrade_list.find(function (item) {
- return item.compilationID === compilationId;
- });
- if (compilationInfo !== undefined && compilationInfo.isUpgrade === true) {
- version = '大司空云计价(专业版)';
- if (compilationInfo.deadline !== undefined && compilationInfo.deadline !== '') {
- deadline = compilationInfo.deadline;
- }
- }
- }
- return {version: version, deadline: deadline};
- }
- /**
- * 判断用户是免费版还是专业版用户
- */
- async isFree(ssoId, compilationId) {
- const userData = await this.findDataBySsoId(ssoId);
- if (!userData) {
- throw '不存在此用户';
- }
- const upgrade_list = userData.upgrade_list;
- let free = true;
- if (upgrade_list && upgrade_list.length > 0) {
- const upgrade = upgrade_list.find(function (item) {
- return item.compilationID === compilationId && item.isUpgrade === true;
- });
- if (upgrade) {
- free = false;
- }
- }
- return free
- }
- /**
- * 从session中判断用户是否是免费版
- * @param {String} sessionVersion
- * @return {Boolean}
- */
- isFreeFromSession(sessionVersion) {
- if (!sessionVersion) {
- return true;
- }
- return sessionVersion.indexOf('免费') >= 0;
- }
- /*
- * 添加联系人,互相添加
- */
- async addContact(userID, contactID) {
- const data = [
- { user: userID, contact: contactID },
- { user: contactID, contact: userID }
- ];
- const task = [];
- for (const { user, contact } of data) {
- const hasThisContact = await this.model.count({_id: mongoose.Types.ObjectId(user), 'contacts.userID': contact});
- // 没有则添加
- if (!hasThisContact) {
- task.push(this.model.update({_id: mongoose.Types.ObjectId(user)}, {$push: {contacts: {userID: contact}}}));
- }
- }
- if (task.length) {
- await Promise.all(task);
- }
- }
- async getContacts(userID) {
- const user = await this.model.findOne({_id: mongoose.Types.ObjectId(userID)}, 'contacts').lean();
- if (!user || !user.contacts || !user.contacts.length) {
- return [];
- }
- const userIDList = user.contacts.map(item => mongoose.Types.ObjectId(item.userID));
- const users = await this.model.find({_id: {$in: userIDList}}, 'real_name mobile company');
- return users;
- }
- /**
- * 获取列表
- *
- * @param {object} condition
- * @param {number} page
- * @param {Number} pageSize
- * @return {promise}
- */
- async getList(condition = null, page = 1, pageSize = 30, sort = {_id:-1}) {
- page = parseInt(page);
- page = page <= 1 ? 1 : page;
- let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize), sort: sort};
- let userList = await this.db.find(condition, null, option);
- userList = userList.length > 0 ? userList : [];
- return userList;
- }
- /**
- * 获取过滤条件
- *
- * @return {Object}
- */
- getFilterCondition(request) {
- let condition = {};
- let regtime = request.query.regtime;
- regtime = regtime !== '' && regtime !== undefined ? parseInt(regtime) : 0;
- if (regtime !== 0) {
- condition.create_time = this.getTimestamp(regtime);
- }
- //最近登录时间
- let loginTime = request.query.loginTime;
- loginTime = loginTime !== '' && loginTime !== undefined ? parseInt(loginTime) : 0;
- if (loginTime !== 0) {
- condition.latest_login = this.getTimestamp(loginTime);
- }
- let version = request.query.version;
- if(version !== '' && version !== undefined) {
- condition.version = version;
- }
- // 已升级费用定额
- let upGrade = request.query.upGrade;
- if(upGrade !== '' && upGrade !== undefined){
- condition.upgrade_list = {"$elemMatch":{"compilationID":upGrade,"isUpgrade":true}};
- }
- // 最近使用费用定额
- let latestUsed = request.query.latestUsed;
- if(latestUsed !== '' && latestUsed !== undefined){
- condition.latest_used = latestUsed;
- }
- let keyword = request.query.keyword;
- if (keyword !== '' && keyword !== undefined) {
- condition.$or = [{real_name : {$regex: keyword}},{email : {$regex: keyword}},{mobile : {$regex: keyword}},{qq : {$regex: keyword}},{company : {$regex: keyword}}];
- }
- return condition;
- }
- /**
- * 获取时间戳区间
- *
- * @return {Object}
- */
- getTimestamp(type) {
- let startTime = '';
- switch (type) {
- case 1 :
- startTime = Date.parse(new Date())-86400*1000;
- break;
- case 2 :
- startTime = Date.parse(new Date())-86400*1000*3;
- break;
- case 3 :
- startTime = Date.parse(new Date())-86400*1000*7;
- break;
- case 4 :
- startTime = Date.parse(new Date())-86400*1000*30;
- break;
- default :
- break;
- }
- let endTime = Date.parse(new Date());
- return startTime === '' ? '' : {'$gte': startTime, '$lt': endTime};
- }
- /**
- * 获取daymsg
- *
- */
- getDayMsg(index){
- return this.dayMsg[index];
- }
- }
- export default UserModel;
|