user.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. /* eslint-disable eqeqeq */
  2. 'use strict';
  3. const shopController = require('./shop.js');
  4. const Decimal = require('decimal.js');
  5. // 用户控制器
  6. module.exports = class UserController extends shopController {
  7. // 使用模型
  8. get useModel() {
  9. const that = this;
  10. return that.app.model.Users;
  11. }
  12. /**
  13. * [registerValidate 用户注册验证器]
  14. * @return {[type]} [description]
  15. */
  16. get registerValidate() {
  17. const that = this;
  18. return {
  19. account_name: that.ctx.rules.name('账号')
  20. .required()
  21. .trim()
  22. .notEmpty(),
  23. password: that.ctx.rules.name('密码')
  24. .required()
  25. .trim()
  26. .notEmpty()
  27. .extend((field, value, row) => {
  28. row[field] = that.app.szjcomo.MD5(value);
  29. }),
  30. create_time: that.ctx.rules.default(that.app.szjcomo.date('Y-m-d H:i:s'))
  31. .required(),
  32. };
  33. }
  34. /**
  35. * [wxRegisterAdnLoginValidate 微信登录和注册验证器]
  36. * @return {[type]} [description]
  37. */
  38. get wxRegisterAdnLoginValidate() {
  39. const that = this;
  40. return {
  41. code: that.ctx.rules.name('微信授权code')
  42. .required()
  43. .notEmpty()
  44. .trim(),
  45. };
  46. }
  47. /**
  48. * [loginValidate 用户登录]
  49. * @return {[type]} [description]
  50. */
  51. get loginValidate() {
  52. const that = this;
  53. return {
  54. account_name: that.ctx.rules.name('用户账号')
  55. .required()
  56. .notEmpty()
  57. .trim(),
  58. password: that.ctx.rules.name('登录密码')
  59. .required()
  60. .notEmpty()
  61. .trim()
  62. .extend((field, value, row) => {
  63. row[field] = that.app.szjcomo.MD5(value);
  64. }),
  65. };
  66. }
  67. /**
  68. * 更新用户信息
  69. * @date:2023/10/20
  70. */
  71. get updateValidate() {
  72. const that = this;
  73. return {
  74. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  75. .number(),
  76. };
  77. }
  78. /**
  79. * [wxuserValidate 微信用户写入]
  80. * @return {[type]} [description]
  81. */
  82. get wxuserValidate() {
  83. const that = this;
  84. return {
  85. nickname: that.ctx.rules.name('用户昵称')
  86. .required()
  87. .notEmpty()
  88. .trim(),
  89. openid: that.ctx.rules.name('openid')
  90. .required()
  91. .notEmpty()
  92. .trim(),
  93. password: that.ctx.rules.default(that.app.szjcomo.MD5('123456'))
  94. .required(),
  95. account_name: that.ctx.rules.default(`${that.app.szjcomo.str_rand(6)}${that.app.szjcomo.date('His')}`)
  96. .required(),
  97. money: that.ctx.rules.default(0)
  98. .number(),
  99. intergral: that.ctx.rules.default(0)
  100. .number(),
  101. headimgurl: that.ctx.rules.default('')
  102. .required(),
  103. login_time: that.ctx.rules.default(that.app.szjcomo.date('Y-m-d H:i:s'))
  104. .required(),
  105. city: that.ctx.rules.default('')
  106. .required(),
  107. province: that.ctx.rules.default('')
  108. .required(),
  109. country: that.ctx.rules.default('')
  110. .required(),
  111. sex: that.ctx.rules.default(0)
  112. .number(),
  113. subscribe: that.ctx.rules.default(0)
  114. .number(),
  115. unionid: that.ctx.rules.default('')
  116. .required(),
  117. create_time: that.ctx.rules.default(that.app.szjcomo.date('Y-m-d H:i:s'))
  118. .required(),
  119. };
  120. }
  121. /**
  122. * [wxloginURLValidate 获取微信登录地址]
  123. * @return {[type]} [description]
  124. */
  125. get wxloginURLValidate() {
  126. const that = this;
  127. return {
  128. page_uri: that.ctx.rules.name('当前地址')
  129. .required()
  130. .notEmpty()
  131. .trim(),
  132. };
  133. }
  134. /**
  135. * [userMoneyValidate 获取用户余额]
  136. * @return {[type]} [description]
  137. */
  138. get userMoneyValidate() {
  139. const that = this;
  140. return {
  141. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  142. .number(),
  143. page: that.ctx.rules.default(1)
  144. .number(),
  145. limit: that.ctx.rules.default(50)
  146. .number(),
  147. };
  148. }
  149. get luckyValidate() {
  150. const that = this;
  151. return {
  152. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  153. .number(),
  154. };
  155. }
  156. get userTransferValidate() {
  157. const that = this;
  158. return {
  159. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  160. .number(),
  161. diningCoinCode: that.ctx.rules.default('')
  162. .required(),
  163. page: that.ctx.rules.default(1)
  164. .number(),
  165. limit: that.ctx.rules.default(50)
  166. .number(),
  167. };
  168. }
  169. get businessCashCoinValidate() {
  170. const that = this;
  171. return {
  172. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  173. .number(),
  174. };
  175. }
  176. // 2023/1/13 提现验证器
  177. get cashOutValidate() {
  178. const that = this;
  179. return {
  180. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  181. .number(),
  182. cash_amount: that.ctx.rules.name('提现金额')
  183. .required()
  184. .notEmpty()
  185. .number(),
  186. remark: that.ctx.rules.name('备注说明')
  187. .default('')
  188. .trim(),
  189. };
  190. }
  191. // 2023/2/28 餐币核销验证
  192. get coinTransferValidate() {
  193. const that = this;
  194. return {
  195. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  196. .number(),
  197. coinAmount: that.ctx.rules.name('核销收取餐币')
  198. .required()
  199. .notEmpty()
  200. .number(),
  201. time: that.ctx.rules.name('餐币二维码刷新时间')
  202. .required()
  203. .notEmpty()
  204. .number(),
  205. diningCoinCode: that.ctx.rules.name('餐币二维码特征')
  206. .required()
  207. .notEmpty(),
  208. };
  209. }
  210. /**
  211. * [login 用户登录 - 账号密码]
  212. * @return {[type]} [description]
  213. */
  214. async login() {
  215. const that = this;
  216. try {
  217. const data = await that.ctx.validate(that.loginValidate, await that.ctx.postParse());
  218. const user = await that.useModel.findOne({
  219. where: { account_name: data.account_name, password: data.password },
  220. // include: [
  221. // { model: that.app.model.ProxyApplyLogs, as: 'proxyApplyLogs', attributes: [ 'verify_status' ] },
  222. // ],
  223. attributes: [ 'user_id', 'account_name', 'nickname', 'headimgurl', 'openid', 'intergral', 'is_proxy', 'partner_id', 'is_office', 'is_family', 'lucky_time' ],
  224. raw: true,
  225. });
  226. if (!user) throw new Error('登录失败,请检查账号密码是否正确');
  227. user.isNew = false;
  228. const result = await that.loginHandle(user);
  229. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  230. } catch (err) {
  231. console.log(err);
  232. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  233. }
  234. }
  235. /**
  236. * [loginHandle 登录处理]
  237. * @param {Object} user [description]
  238. * @return {[type]} [description]
  239. */
  240. async loginHandle(user = {}) {
  241. const that = this;
  242. const token = that.app.jwt.sign(user, that.app.config.jwt.secret, { expiresIn: '24h' });
  243. const result = { token, user };
  244. return result;
  245. }
  246. /**
  247. * [register 用户注册]
  248. * @return {[type]} [description]
  249. */
  250. async register() {
  251. const that = this;
  252. try {
  253. const data = await that.ctx.validate(that.registerValidate, await that.ctx.postParse());
  254. const createBean = that.app.comoBean.instance(data, {});
  255. const result = await that.service.manager.create(createBean, that.useModel, '注册失败,请稍候重试');
  256. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  257. } catch (err) {
  258. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  259. }
  260. }
  261. /**
  262. * [wxRegisterAdnLogin 用户登录 - 微信注册登录]
  263. * @return {[type]} [description]
  264. */
  265. async wxRegisterAdnLogin() {
  266. const that = this;
  267. try {
  268. const appid = await that.service.configs.getConfigValue('wechat_account_appid');
  269. const secret = await that.service.configs.getConfigValue('wechat_account_secret');
  270. const data = await that.ctx.validate(that.wxRegisterAdnLoginValidate, await that.ctx.getParse());
  271. const result = await that.service.wechat.authLogin(appid, secret, data.code);
  272. if (result.errcode) throw new Error(`微信通讯失败,错误信息:${result.errmsg}`);
  273. const userInfo = await that.service.wechat.authUserInfo(result);
  274. const user = await that.wxRegisterAdnLoginHandle(userInfo, data.inviteCode);
  275. const loginRes = await that.loginHandle(user);
  276. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', loginRes, false));
  277. } catch (err) {
  278. await that.logs('user.js', err);
  279. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  280. }
  281. }
  282. /**
  283. * [wxloginURL 微信登录地址]
  284. * @return {[type]} [description]
  285. */
  286. async wxloginURL() {
  287. const that = this;
  288. try {
  289. const data = await that.ctx.validate(that.wxloginURLValidate, await that.ctx.postParse());
  290. const appid = await that.service.configs.getConfigValue('wechat_account_appid');
  291. const curarr = data.page_uri.split('#');
  292. const result = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(curarr[0] + '#/shop/wxauth')}&response_type=code&scope=snsapi_userinfo&state=${that.app.szjcomo.base64_encode(data.page_uri)}#wechat_redirect`;
  293. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  294. } catch (err) {
  295. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  296. }
  297. }
  298. /**
  299. * [wxRegisterAdnLoginHandle 注册并登录]
  300. * @param {Object} userInfo [description]
  301. * @param {Number} inviteCode
  302. * @return {[type]} [description]
  303. */
  304. async wxRegisterAdnLoginHandle(userInfo = {}, inviteCode = -1) {
  305. const that = this;
  306. const inviter_id = inviteCode;
  307. // console.log('==========inviteCode========== : ' + inviter_id);
  308. const options = {
  309. where: { openid: userInfo.openid },
  310. attributes: [ 'user_id', 'account_name', 'nickname', 'headimgurl', 'openid', 'partner_id', 'is_office', 'is_family', 'lucky_time' ],
  311. raw: true,
  312. };
  313. let user = await that.useModel.findOne(options);
  314. if (!user) {
  315. // 2022/9/27 新用户注册 写入信息
  316. user = await that.writeWxUser(userInfo);
  317. user.isNew = true;
  318. // 2022/9/27: 新用户红包奖励8.8元
  319. await that.service.shop.userMoneyAdd(user.user_id, 8.8, null, '新用户注册奖励', 0, 1, -1);
  320. // 2022/9/29 受邀注册奖励 和 邀请新用户奖励
  321. if (inviter_id > 0) {
  322. try {
  323. const inviterInfo = await that.useModel.findOne({
  324. where: { user_id: inviter_id },
  325. attributes: [ 'user_id', 'nickname', 'headimgurl' ],
  326. raw: true,
  327. });
  328. await that.service.shop.userMoneyAdd(user.user_id, 1.68, null, '受邀注册奖励', 0, 2, inviter_id, inviterInfo.nickname, inviterInfo.headimgurl);
  329. await that.service.shop.userMoneyAdd(inviter_id, 1.68, null, '邀请新用户奖励', 0, 3, user.user_id, user.nickname, user.headimgurl);
  330. // 2022/11/17 邀请关系绑定
  331. await that.service.inviter.addRelUserInviter(user.user_id, inviter_id);
  332. } catch (e) {
  333. // 邀请人id不存在
  334. }
  335. }
  336. } else {
  337. user.isNew = false;
  338. // 2023/8/25 更新登录时间
  339. const updateBean = await that.app.comoBean.instance({
  340. login_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  341. update_ttime: that.app.szjcomo.date('Y-m-d H:i:s'),
  342. unionid: userInfo.unionid,
  343. }, { where: { user_id: user.user_id } });
  344. await that.service.base.update(updateBean, that.useModel, '微信用户登录时间更新失败,请重试');
  345. }
  346. return user;
  347. }
  348. /**
  349. * [writeWxUser 写入微信用户]
  350. * @param {Object} userInfo [description]
  351. * @return {[type]} [description]
  352. */
  353. async writeWxUser(userInfo = {}) {
  354. const that = this;
  355. const data = await that.ctx.validate(that.wxuserValidate, userInfo);
  356. const createBean = await that.app.comoBean.instance(data);
  357. const result = await that.service.base.create(createBean, that.useModel, '添加微信用户失败,请重试');
  358. return {
  359. user_id: result.dataValues.user_id,
  360. account_name: result.dataValues.account_name,
  361. nickname: result.dataValues.nickname,
  362. headimgurl: result.dataValues.headimgurl,
  363. openid: result.dataValues.openid,
  364. unionid: result.dataValues.unionid,
  365. is_office: result.dataValues.is_office,
  366. is_family: result.dataValues.is_family,
  367. };
  368. }
  369. /**
  370. * [userMoney 获取用户余额]
  371. * @return {[type]} [description]
  372. */
  373. async userMoney() {
  374. const that = this;
  375. try {
  376. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  377. const result = await that.service.shop.getUserMoney(data.user_id);
  378. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  379. } catch (err) {
  380. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  381. }
  382. }
  383. /**
  384. * [userMoney 获取用户账户余额]
  385. * @return {[type]} [description]
  386. */
  387. async userAccount() {
  388. const that = this;
  389. try {
  390. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  391. const result = await that.service.shop.getUserAccount(data.user_id);
  392. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  393. } catch (err) {
  394. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  395. }
  396. }
  397. /**
  398. * [userMoneyLog 用户资金明细]
  399. * @return {[type]} [description]
  400. */
  401. async userMoneyLog() {
  402. const that = this;
  403. try {
  404. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  405. const selectBean = await that.app.comoBean.instance(data, {
  406. offset: (data.page - 1) * data.limit,
  407. limit: data.limit,
  408. where: { user_id: data.user_id },
  409. order: [ [ 'log_id', 'desc' ] ],
  410. attributes: [ 'log_id', 'log_desc', 'change_time', 'money', 'type', 'inviter_id', 'inviter_name', 'inviter_img' ],
  411. });
  412. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '查询资金明细失败,请稍候重试', true, true);
  413. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  414. } catch (err) {
  415. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  416. }
  417. }
  418. /**
  419. * [userMoneyLog 用户分佣明细]
  420. * @return {[type]} [description]
  421. */
  422. async userCommissionLog() {
  423. const that = this;
  424. try {
  425. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  426. const selectBean = await that.app.comoBean.instance(data, {
  427. // offset: (data.page - 1) * data.limit, limit: data.limit,
  428. where: { user_id: data.user_id },
  429. order: [ [ 'log_id', 'desc' ] ],
  430. attributes: [ 'log_desc', 'create_time', 'commission', 'type', 'inviter_id', 'inviter_name', 'inviter_img' ],
  431. });
  432. // 2022/11/28 直接查询所有数据 不分页
  433. const result = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询分佣明细失败,请稍候重试', false, true);
  434. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  435. } catch (err) {
  436. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  437. }
  438. }
  439. /**
  440. * [userMoneyLog 用户餐币明细]
  441. * @return {[type]} [description]
  442. */
  443. async coinDetail() {
  444. const that = this;
  445. try {
  446. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  447. const selectBean = await that.app.comoBean.instance(data, {
  448. where: { user_id: data.user_id },
  449. order: [ [ 'log_id', 'desc' ] ],
  450. });
  451. // 2022/11/28 直接查询所有数据 不分页
  452. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询分佣明细失败,请稍候重试', false, true);
  453. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  454. } catch (err) {
  455. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  456. }
  457. }
  458. // 2023/2/28 用户餐饮币账户列表
  459. async userDiningCoin() {
  460. const that = this;
  461. try {
  462. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  463. const selectBean = await that.app.comoBean.instance(data, {
  464. where: { user_id: data.user_id, expired: false },
  465. });
  466. // 2023/2/28 直接查询所有数据 不分页
  467. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户失败,请稍候重试', false, true);
  468. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  469. } catch (err) {
  470. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  471. }
  472. }
  473. /**
  474. * 用户指定商家餐币账户余额
  475. * @return {Promise<*>}
  476. */
  477. async userCouldTransferCoin() {
  478. const that = this;
  479. try {
  480. const data = await that.ctx.validate(that.userTransferValidate, await that.ctx.getParse());
  481. const res = await that.getCouldTransferCoin(data);
  482. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', { couldTransferCoins: res.account }, false));
  483. } catch (err) {
  484. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  485. }
  486. }
  487. /**
  488. * 用户可在指定商家消费的餐币账户余额
  489. * @param data
  490. */
  491. async getCouldTransferCoin(data) {
  492. const that = this;
  493. if (!data.diningCoinCode) {
  494. throw new Error('参数错误');
  495. }
  496. const userInfo = await that.app.model.Users.findOne({
  497. where: { openid: data.diningCoinCode },
  498. attributes: [ 'user_id' ],
  499. });
  500. if (!userInfo || userInfo.user_id < 0) {
  501. throw new Error('参数错误');
  502. }
  503. const businessInfo = await that.app.model.Users.findOne({
  504. where: { user_id: data.user_id },
  505. attributes: [ 'partner_id' ],
  506. });
  507. if (!businessInfo || businessInfo.partner_id < 1) {
  508. throw new Error('抱歉,您不是源森家具的合作商户,无权收款。');
  509. }
  510. const seq = that.app.Sequelize;
  511. const selectBean = await that.app.comoBean.instance({}, {
  512. where: {
  513. user_id: userInfo.user_id,
  514. // partner_id: businessInfo.partner_id,
  515. // 2023/4/11 补充通用餐币
  516. partner_id: { [seq.Op.in]: [ businessInfo.partner_id, 1 ] },
  517. expired: false,
  518. },
  519. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  520. });
  521. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户余额失败,请稍候重试', false, false);
  522. const res = JSON.parse(JSON.stringify(result));
  523. res.customer_id = userInfo.user_id;
  524. res.partner_id = businessInfo.partner_id;
  525. res.business_id = data.user_id;
  526. return res;
  527. }
  528. /**
  529. * 商家可提现餐币金额
  530. * @return {Promise<*>}
  531. */
  532. async businessDiningCoinCouldCash() {
  533. const that = this;
  534. try {
  535. const data = await that.ctx.validate(that.businessCashCoinValidate, await that.ctx.getParse());
  536. const res = await that.getDiningCoinCouldCash(data);
  537. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', res, false));
  538. } catch (err) {
  539. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  540. }
  541. }
  542. /**
  543. * 商家可提现餐币金额
  544. * @param data
  545. */
  546. async getDiningCoinCouldCash(data) {
  547. const that = this;
  548. const businessInfo = await that.app.model.Users.findOne({
  549. where: { user_id: data.user_id },
  550. });
  551. if (!businessInfo || businessInfo.partner_id < 0) {
  552. throw new Error('您的账号还没有绑定的合作商铺哦');
  553. }
  554. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  555. where: { id: businessInfo.partner_id },
  556. });
  557. if (!partnerInfo || partnerInfo.user_id !== data.user_id) {
  558. throw new Error('您的账号没有权限提现餐费哦');
  559. }
  560. const seq = that.app.Sequelize;
  561. const currentDateTime = that.app.szjcomo.date('Y-m-d H:i:s');
  562. const sevenDayTime = 24 * 60 * 60 * 1000; // 2023/3/1 24小时后可提现
  563. const endTimeStamp = Date.parse(currentDateTime) - sevenDayTime;
  564. const endDateTime = that.app.szjcomo.date('Y-m-d H:i:s', endTimeStamp / 1000);
  565. // 2023/3/1 查询24小时前的所得餐币总和 以及所有时间提现的总和 再求和 即为 可提现餐币金额
  566. // todo : 特殊情况 商家管理员有自家绑定的商铺 餐币消费支出
  567. const selectBean = await that.app.comoBean.instance({}, {
  568. where: {
  569. user_id: businessInfo.user_id,
  570. partner_id: businessInfo.partner_id,
  571. create_time: { [seq.Op.lte]: endDateTime },
  572. account: { [seq.Op.gte]: 0 },
  573. },
  574. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  575. });
  576. const coinResult = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  577. const selectBean2 = await that.app.comoBean.instance({}, {
  578. where: {
  579. user_id: businessInfo.user_id,
  580. partner_id: businessInfo.partner_id,
  581. account: { [seq.Op.lte]: 0 },
  582. type: { [seq.Op.ne]: -1 },
  583. },
  584. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  585. });
  586. const cashResult = await that.service.base.select(selectBean2, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  587. const coinRes = JSON.parse(JSON.stringify(coinResult));
  588. const cashRes = JSON.parse(JSON.stringify(cashResult));
  589. const couldCash = new Decimal(coinRes.account ? coinRes.account : 0)
  590. .add(new Decimal(cashRes.account ? cashRes.account : 0))
  591. .toNumber();
  592. coinRes.all_coin_could_cash = couldCash > 0 ? couldCash : 0;
  593. coinRes.all_cash = cashRes.account;
  594. coinRes.partner_id = businessInfo.partner_id;
  595. coinRes.partner_fees = partnerInfo.partner_fees;
  596. return coinRes;
  597. }
  598. /**
  599. * 商家申请核销餐币
  600. * @return {Promise<void>}
  601. */
  602. async coinTransfer() {
  603. const that = this;
  604. const seq = that.app.Sequelize;
  605. const transaction = await that.app.model.transaction();
  606. try {
  607. const data = await that.ctx.validate(that.coinTransferValidate, await that.ctx.postParse());
  608. // 2023/2/28 获取可核销餐币
  609. const intervalTime = Date.parse(that.app.szjcomo.date('Y-m-d H:i:s')) - data.time;
  610. if (intervalTime > 10 * 60 * 1000) {
  611. throw new Error('顾客付款码已超时失效,请重新扫码!');
  612. }
  613. const transferParams = await that.getCouldTransferCoin(data);
  614. if (data.coinAmount > 0 && data.coinAmount <= transferParams.account) {
  615. // 2023/2/28 发起核销收取餐币
  616. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  617. where: { id: transferParams.partner_id },
  618. });
  619. // 2023/4/12 核销餐币 包含通用电子餐币
  620. const selectBean = await that.app.comoBean.instance({}, {
  621. where: {
  622. user_id: transferParams.customer_id,
  623. // partner_id: transferParams.partner_id,
  624. partner_id: { [seq.Op.in]: [ transferParams.partner_id, 1 ] },
  625. expired: false,
  626. },
  627. order: [ [ 'partner_id', 'desc' ], [ 'ori_partner', 'desc' ] ],
  628. });
  629. // 2023/2/28 查询所有指定商家餐币
  630. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户失败,请稍候重试', false, true);
  631. const customerAccounts = [];
  632. let needAccount = 0;
  633. for (const resultElement of result) {
  634. needAccount += resultElement.account;
  635. customerAccounts.push(JSON.parse(JSON.stringify(resultElement)));
  636. if (needAccount >= data.coinAmount) {
  637. break;
  638. }
  639. }
  640. let firstCoinAmount;
  641. let secondCoinAmount;
  642. let thirdCoinAmount;
  643. let fourthCoinAmount;
  644. let incomeCoinAmount = 0;
  645. switch (customerAccounts.length) {
  646. case 1:
  647. firstCoinAmount = data.coinAmount;
  648. secondCoinAmount = 0;
  649. thirdCoinAmount = 0;
  650. fourthCoinAmount = 0;
  651. break;
  652. case 2:
  653. firstCoinAmount = customerAccounts[0].account;
  654. secondCoinAmount = data.coinAmount - firstCoinAmount;
  655. thirdCoinAmount = 0;
  656. fourthCoinAmount = 0;
  657. break;
  658. case 3:
  659. firstCoinAmount = customerAccounts[0].account;
  660. secondCoinAmount = customerAccounts[1].account;
  661. thirdCoinAmount = data.coinAmount - firstCoinAmount - secondCoinAmount;
  662. fourthCoinAmount = 0;
  663. break;
  664. case 4:
  665. firstCoinAmount = customerAccounts[0].account;
  666. secondCoinAmount = customerAccounts[1].account;
  667. thirdCoinAmount = customerAccounts[2].account;
  668. fourthCoinAmount = data.coinAmount - firstCoinAmount - secondCoinAmount - thirdCoinAmount;
  669. break;
  670. default:
  671. break;
  672. }
  673. // =========================================== 2023/3/1 第一个账户划账======================================
  674. await that.doTransferCoins(that, transferParams, firstCoinAmount, partnerInfo, transaction, customerAccounts, 0);
  675. incomeCoinAmount += firstCoinAmount * (customerAccounts[0].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  676. // =============================== 2023/3/1 需要第二个账户来继续划账 ==========================================
  677. if (customerAccounts.length > 1 && secondCoinAmount > 0) {
  678. await that.doTransferCoins(that, transferParams, secondCoinAmount, partnerInfo, transaction, customerAccounts, 1);
  679. incomeCoinAmount += secondCoinAmount * (customerAccounts[1].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  680. }
  681. // =============================== 2023/3/18 需要第三个账户来继续划账 ==========================================
  682. if (customerAccounts.length > 2 && thirdCoinAmount > 0) {
  683. await that.doTransferCoins(that, transferParams, thirdCoinAmount, partnerInfo, transaction, customerAccounts, 2);
  684. incomeCoinAmount += thirdCoinAmount * (customerAccounts[2].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  685. }
  686. // =============================== 2023/3/18 需要第四个账户来继续划账 ==========================================
  687. if (customerAccounts.length > 3 && fourthCoinAmount > 0) {
  688. await that.doTransferCoins(that, transferParams, fourthCoinAmount, partnerInfo, transaction, customerAccounts, 3);
  689. incomeCoinAmount += fourthCoinAmount * (customerAccounts[3].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  690. }
  691. await transaction.commit();
  692. incomeCoinAmount = incomeCoinAmount.toFixed(2);
  693. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', {
  694. incomeCoinAmount,
  695. transferCoinAmount: data.coinAmount,
  696. }, false));
  697. }
  698. throw new Error('输入的核销金额有误,请稍后重试');
  699. } catch (e) {
  700. if (transaction) transaction.rollback();
  701. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  702. }
  703. }
  704. // 2023/3/1 餐币划账 具体逻辑和操作
  705. async doTransferCoins(that, transferParams, coinAmount, partnerInfo, transaction, customerAccounts, index) {
  706. // 2023/3/6 获取顾客信息
  707. const customerInfo = await that.app.model.Users.findOne({
  708. where: { user_id: transferParams.customer_id },
  709. transaction,
  710. raw: true,
  711. });
  712. // 2023/3/1 扣去顾客餐币
  713. await that.service.diningCoin.addDiningCoinChangeLog({
  714. user_id: transferParams.customer_id,
  715. order_id: -1,
  716. partner_id: customerAccounts[index].partner_id,
  717. type: 3,
  718. account: -coinAmount,
  719. log_desc: partnerInfo.name + ' 消费',
  720. }, transaction);
  721. // 2023/3/1 更新顾客账户
  722. const customerAccountBean = await that.app.comoBean.instance({
  723. account: customerAccounts[index].account - coinAmount,
  724. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  725. }, {
  726. where: {
  727. user_id: transferParams.customer_id,
  728. ori_partner: customerAccounts[index].ori_partner,
  729. partner_id: customerAccounts[index].partner_id,
  730. expired: false,
  731. }, transaction,
  732. });
  733. if (customerAccounts[index].account === coinAmount) {
  734. // 2023/3/1 删除0元账户
  735. await that.service.base.delete(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币清零更新失败,请重试');
  736. } else {
  737. await that.service.base.update(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币余额更新失败,请重试');
  738. }
  739. // 2023/3/1 划入商家账户记录
  740. const businessCoinAmount = coinAmount * (customerAccounts[index].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  741. await that.service.diningCoin.addDiningCoinChangeLog({
  742. user_id: transferParams.business_id,
  743. order_id: -1,
  744. partner_id: transferParams.partner_id,
  745. type: 4,
  746. account: businessCoinAmount,
  747. log_desc: '核销收取餐币',
  748. ori_partner: customerAccounts[index].ori_partner,
  749. customer_id: customerInfo.user_id,
  750. customer_name: customerInfo.nickname,
  751. customer_img: customerInfo.headimgurl,
  752. }, transaction);
  753. // 2023/2/28 查询商家餐饮币账户列表 添加 或 更新账户余额
  754. const info = await that.app.model.DinnerCoins.findOne({
  755. where: {
  756. user_id: transferParams.business_id,
  757. // ori_partner: customerAccounts[index].ori_partner,
  758. partner_id: transferParams.partner_id,
  759. expired: false,
  760. },
  761. transaction,
  762. raw: true,
  763. });
  764. if (!info) {
  765. // 2023/2/27 没有对应类型的餐饮币 则插入该类型的餐饮币账户
  766. const createData = {
  767. user_id: transferParams.business_id,
  768. account: businessCoinAmount,
  769. // ori_partner: customerAccounts[index].ori_partner,
  770. ori_partner: true,
  771. partner_id: transferParams.partner_id,
  772. create_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  773. expired: false,
  774. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  775. };
  776. createData.partner_name = partnerInfo.name;
  777. createData.partner_address = partnerInfo.address;
  778. createData.partner_tel = partnerInfo.tel_num;
  779. createData.partner_opening_time = partnerInfo.opening_time;
  780. const createBean = await that.app.comoBean.instance(createData, { transaction });
  781. await that.service.base.create(createBean, that.app.model.DinnerCoins, '餐饮币发放失败,请重试');
  782. } else {
  783. const updateBean = await that.app.comoBean.instance({
  784. account: info.account + businessCoinAmount,
  785. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  786. expired: false,
  787. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  788. }, {
  789. where: {
  790. user_id: transferParams.business_id,
  791. // ori_partner: customerAccounts[index].ori_partner,
  792. partner_id: transferParams.partner_id,
  793. }, transaction,
  794. });
  795. await that.service.base.update(updateBean, that.app.model.DinnerCoins, '餐饮币余额更新失败,请重试');
  796. }
  797. }
  798. /**
  799. * 用户可提现金额(求和)
  800. * @return {Promise<*>}
  801. */
  802. async userCommissionCouldCash() {
  803. const that = this;
  804. try {
  805. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  806. const result = await that.getCouldCashCommission(data.user_id);
  807. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  808. } catch (err) {
  809. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  810. }
  811. }
  812. /**
  813. * 获取用户可提现金额(求和)
  814. * todo 判断订单状态 确认收货的订单才能提现
  815. * @return {Promise<void>}
  816. */
  817. async getCouldCashCommission(user_id = -1) {
  818. if (user_id <= 0) {
  819. throw new Error('参数错误');
  820. }
  821. const that = this;
  822. const seq = that.app.Sequelize;
  823. const currentDateTime = that.app.szjcomo.date('Y-m-d H:i:s');
  824. const sevenDayTime = 7 * 24 * 60 * 60 * 1000;
  825. const endTimeStamp = Date.parse(currentDateTime) - sevenDayTime;
  826. const endDateTime = that.app.szjcomo.date('Y-m-d H:i:s', endTimeStamp / 1000);
  827. // 2022/11/28 查询7天前的所得分佣总和 以及所有时间得提现总和 再求和 即为 可提现金额
  828. const selectBean = await that.app.comoBean.instance({ user_id }, {
  829. where: { user_id, create_time: { [seq.Op.lte]: endDateTime }, commission: { [seq.Op.gte]: 0 } },
  830. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_commission' ] ],
  831. });
  832. const commissionResult = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  833. const selectBean2 = await that.app.comoBean.instance({ user_id }, {
  834. where: { user_id, commission: { [seq.Op.lte]: 0 }, type: { [seq.Op.ne]: -1 } }, // type-1提现失败类型
  835. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_cash' ] ],
  836. });
  837. const cashResult = await that.service.base.select(selectBean2, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  838. const commRes = JSON.parse(JSON.stringify(commissionResult));
  839. const cashRes = JSON.parse(JSON.stringify(cashResult));
  840. commRes.all_commission_could_cash = new Decimal(commRes.all_commission ? commRes.all_commission : 0)
  841. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  842. .toNumber();
  843. commRes.all_cash = cashRes.all_cash;
  844. return commRes;
  845. }
  846. /**
  847. * 用户佣金提现
  848. * TODO 提现条件 分佣对应订单状态 确认收货 方可提现
  849. * @return {Promise<void>}
  850. */
  851. async userCashOut() {
  852. const that = this;
  853. try {
  854. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  855. // 2023/1/17 获取可提现佣金额度
  856. const res = await that.getCouldCashCommission(data.user_id);
  857. if (data.cash_amount >= 0.1 && data.cash_amount <= res.all_commission_could_cash) {
  858. // 2023/1/31 发起提现
  859. const result = await that.service.wxPay.transfer(data);
  860. // 2023/1/31 提现状态
  861. if (result.status != 200) {
  862. throw new Error('提现转账出现异常,请联系客服后再重试');
  863. }
  864. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  865. }
  866. throw new Error('输入提现金额有误,请稍后重试');
  867. } catch (e) {
  868. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  869. }
  870. }
  871. /**
  872. * 用户佣金转电子餐费
  873. * @return {Promise<void>}
  874. */
  875. async commission2DiningCoin() {
  876. // 2023/11/17 todo: 佣金转电子餐费
  877. }
  878. /**
  879. * 商家餐币提现
  880. * @return {Promise<*>}
  881. */
  882. async userCoinCashOut() {
  883. const that = this;
  884. try {
  885. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  886. // 2023/1/17 获取可提现佣金额度
  887. const res = await that.getDiningCoinCouldCash(data);
  888. data.partner_id = res.partner_id;
  889. if (data.cash_amount >= 0.1 && data.cash_amount <= (res.all_coin_could_cash - res.partner_fees)) {
  890. // 2023/1/31 发起提现
  891. const result = await that.service.businessPayService.transfer(data);
  892. // 2023/1/31 提现状态
  893. if (result.status != 200) {
  894. throw new Error('提现转账出现异常,请联系客服后再重试');
  895. }
  896. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  897. }
  898. throw new Error('输入提现金额有误,请稍后重试');
  899. } catch (e) {
  900. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  901. }
  902. }
  903. /**
  904. * [newUserBenefits 查询新用户福利]
  905. * @return {[type]} [description]
  906. */
  907. async newUserBenefits() {
  908. const that = this;
  909. try {
  910. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  911. const seq = that.app.Sequelize;
  912. const selectBean = await that.app.comoBean.instance(data, {
  913. offset: (data.page - 1) * data.limit, limit: data.limit, where: {
  914. user_id: data.user_id,
  915. type: { [seq.Op.in]: [ 1, 2 ] },
  916. },
  917. order: [ [ 'type', 'asc' ] ],
  918. });
  919. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '新用户福利查询失败,请稍候重试', true, true);
  920. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  921. } catch (err) {
  922. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  923. }
  924. }
  925. /**
  926. * [newUserBenefits 获取每日红包]
  927. * @return {[type]} [description]
  928. */
  929. async dayLucky() {
  930. const that = this;
  931. try {
  932. const data = await that.ctx.validate(that.luckyValidate, await that.ctx.anyParse());
  933. // 2023/11/17 用户今天是否已经抽奖
  934. const user = await that.useModel.findOne({
  935. where: { user_id: data.user_id },
  936. });
  937. const isTodayLucky = await that.service.baseUtils.isToday(user.lucky_time);
  938. // const isTodayLucky = false;
  939. if (isTodayLucky) {
  940. throw new Error('您今天已经抽奖了哦,明天再来吧!');
  941. } else {
  942. // 2023/11/17 : 发起概率抽奖 发放奖项 (红包上限)
  943. let prizes;
  944. if (user.money > 999) {
  945. prizes = [
  946. { reward: 6, weight: 1 },
  947. { reward: 1, weight: 95 },
  948. { reward: 10, weight: 1 },
  949. { reward: 8, weight: 1 },
  950. { reward: 30, weight: 1 },
  951. { reward: 20, weight: 1 }
  952. ];
  953. } else {
  954. prizes = [
  955. { reward: 6, weight: 4 },
  956. { reward: 1, weight: 1 },
  957. { reward: 10, weight: 50 },
  958. { reward: 8, weight: 10 },
  959. { reward: 30, weight: 5 },
  960. { reward: 20, weight: 30 }
  961. ];
  962. }
  963. const prizeAward = await that.lottery(prizes);
  964. // 2023/11/21 发放红包奖励
  965. // console.log(prizeAward);
  966. await that.service.shop.userMoneyAdd(user.user_id, prizeAward.reward, null, '每日抽奖红包', 0, 4);
  967. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', prizeAward, false));
  968. }
  969. } catch (err) {
  970. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  971. }
  972. }
  973. //权重抽奖函数
  974. async lottery(prizes) {
  975. let total = 0;
  976. let percent;
  977. //下标标记数组
  978. let index = [];
  979. for (let i = 0; i < prizes.length; i++) {
  980. //判断元素的权重,为了实现小数权重,先将所有的值放大100倍
  981. percent = 'undefined' != typeof (prizes[i].weight) ? prizes[i].weight : 0;
  982. for (let j = 0; j < percent; j++) {
  983. index.push(i);
  984. }
  985. total += percent;
  986. }
  987. //随机数值
  988. let rand = Math.floor(Math.random() * total);
  989. return prizes[index[rand]];
  990. };
  991. /**
  992. * 更新用户信息
  993. * @date:2023/10/20
  994. */
  995. async updateUserInfo() {
  996. const that = this;
  997. try {
  998. const data = await that.ctx.validate(that.updateValidate, await that.ctx.anyParse());
  999. // 2023/10/20 更新用户信息
  1000. const dataParam = {};
  1001. if (data.is_office) {
  1002. dataParam.is_office = true;
  1003. }
  1004. if (data.is_family) {
  1005. dataParam.is_family = true;
  1006. }
  1007. dataParam.update_ttime = that.app.szjcomo.date('Y-m-d H:i:s');
  1008. const updateBean = await that.app.comoBean.instance(dataParam, { where: { user_id: data.user_id } });
  1009. const result = await that.service.base.update(updateBean, that.useModel, '微信用户信息更新失败,请重试');
  1010. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  1011. } catch (e) {
  1012. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  1013. }
  1014. }
  1015. };