user.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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. * @return {Promise<void>}
  815. */
  816. async getCouldCashCommission(user_id = -1) {
  817. if (user_id <= 0) {
  818. throw new Error('参数错误');
  819. }
  820. const that = this;
  821. const seq = that.app.Sequelize;
  822. const currentDateTime = that.app.szjcomo.date('Y-m-d H:i:s');
  823. const sevenDayTime = 7 * 24 * 60 * 60 * 1000;
  824. const endTimeStamp = Date.parse(currentDateTime) - sevenDayTime;
  825. const endDateTime = that.app.szjcomo.date('Y-m-d H:i:s', endTimeStamp / 1000);
  826. // 2022/11/28 查询7天前的所得分佣总和 以及所有时间得提现总和 再求和 即为 可提现金额
  827. const selectBean = await that.app.comoBean.instance({ user_id }, {
  828. where: { user_id, create_time: { [seq.Op.lte]: endDateTime }, commission: { [seq.Op.gte]: 0 } },
  829. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_commission' ] ],
  830. });
  831. const commissionResult = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  832. const selectBean2 = await that.app.comoBean.instance({ user_id }, {
  833. where: { user_id, commission: { [seq.Op.lte]: 0 }, type: { [seq.Op.ne]: -1 } }, // type-1提现失败类型
  834. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_cash' ] ],
  835. });
  836. const cashResult = await that.service.base.select(selectBean2, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  837. const commRes = JSON.parse(JSON.stringify(commissionResult));
  838. const cashRes = JSON.parse(JSON.stringify(cashResult));
  839. commRes.all_commission_could_cash = new Decimal(commRes.all_commission ? commRes.all_commission : 0)
  840. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  841. .toNumber();
  842. commRes.all_cash = cashRes.all_cash;
  843. return commRes;
  844. }
  845. /**
  846. * 用户佣金提现
  847. * @return {Promise<void>}
  848. */
  849. async userCashOut() {
  850. const that = this;
  851. try {
  852. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  853. // 2023/1/17 获取可提现佣金额度
  854. const res = await that.getCouldCashCommission(data.user_id);
  855. if (data.cash_amount >= 0.1 && data.cash_amount <= res.all_commission_could_cash) {
  856. // 2023/1/31 发起提现
  857. // todo : 用户分佣提现 1.扣取税费;2.用户分佣转通用电子餐费;
  858. const result = await that.service.wxPay.transfer(data);
  859. // 2023/1/31 提现状态
  860. if (result.status != 200) {
  861. throw new Error('提现转账出现异常,请联系客服后再重试');
  862. }
  863. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  864. }
  865. throw new Error('输入提现金额有误,请稍后重试');
  866. } catch (e) {
  867. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  868. }
  869. }
  870. /**
  871. * 用户佣金转电子餐费
  872. * @return {Promise<void>}
  873. */
  874. async commission2DiningCoin() {
  875. // 2023/11/17 todo: 佣金转电子餐费
  876. }
  877. /**
  878. * 商家餐币提现
  879. * @return {Promise<*>}
  880. */
  881. async userCoinCashOut() {
  882. const that = this;
  883. try {
  884. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  885. // 2023/1/17 获取可提现佣金额度
  886. const res = await that.getDiningCoinCouldCash(data);
  887. data.partner_id = res.partner_id;
  888. if (data.cash_amount >= 0.1 && data.cash_amount <= (res.all_coin_could_cash - res.partner_fees)) {
  889. // 2023/1/31 发起提现
  890. const result = await that.service.businessPayService.transfer(data);
  891. // 2023/1/31 提现状态
  892. if (result.status != 200) {
  893. throw new Error('提现转账出现异常,请联系客服后再重试');
  894. }
  895. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  896. }
  897. throw new Error('输入提现金额有误,请稍后重试');
  898. } catch (e) {
  899. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  900. }
  901. }
  902. /**
  903. * [newUserBenefits 查询新用户福利]
  904. * @return {[type]} [description]
  905. */
  906. async newUserBenefits() {
  907. const that = this;
  908. try {
  909. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  910. const seq = that.app.Sequelize;
  911. const selectBean = await that.app.comoBean.instance(data, {
  912. offset: (data.page - 1) * data.limit, limit: data.limit, where: {
  913. user_id: data.user_id,
  914. type: { [seq.Op.in]: [ 1, 2 ] },
  915. },
  916. order: [ [ 'type', 'asc' ] ],
  917. });
  918. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '新用户福利查询失败,请稍候重试', true, true);
  919. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  920. } catch (err) {
  921. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  922. }
  923. }
  924. /**
  925. * [newUserBenefits 获取每日红包]
  926. * @return {[type]} [description]
  927. */
  928. async dayLucky() {
  929. const that = this;
  930. try {
  931. const data = await that.ctx.validate(that.luckyValidate, await that.ctx.anyParse());
  932. // 2023/11/17 用户今天是否已经抽奖
  933. const user = await that.useModel.findOne({
  934. where: { user_id: data.user_id },
  935. });
  936. const isTodayLucky = await that.service.baseUtils.isToday(user.lucky_time);
  937. // const isTodayLucky = false;
  938. if (isTodayLucky) {
  939. throw new Error('您今天已经抽奖了哦,明天再来吧!');
  940. } else {
  941. // 2023/11/17 : 发起概率抽奖 发放奖项 (红包上限)
  942. let prizes;
  943. if (user.money > 999) {
  944. prizes = [
  945. { reward: 6, weight: 1 },
  946. { reward: 1, weight: 95 },
  947. { reward: 10, weight: 1 },
  948. { reward: 8, weight: 1 },
  949. { reward: 30, weight: 1 },
  950. { reward: 20, weight: 1 }
  951. ];
  952. } else {
  953. prizes = [
  954. { reward: 6, weight: 4 },
  955. { reward: 1, weight: 1 },
  956. { reward: 10, weight: 50 },
  957. { reward: 8, weight: 10 },
  958. { reward: 30, weight: 5 },
  959. { reward: 20, weight: 30 }
  960. ];
  961. }
  962. const prizeAward = await that.lottery(prizes);
  963. // 2023/11/21 发放红包奖励
  964. // console.log(prizeAward);
  965. await that.service.shop.userMoneyAdd(user.user_id, prizeAward.reward, null, '每日抽奖红包', 0, 4);
  966. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', prizeAward, false));
  967. }
  968. } catch (err) {
  969. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  970. }
  971. }
  972. //权重抽奖函数
  973. async lottery(prizes) {
  974. let total = 0;
  975. let percent;
  976. //下标标记数组
  977. let index = [];
  978. for (let i = 0; i < prizes.length; i++) {
  979. //判断元素的权重,为了实现小数权重,先将所有的值放大100倍
  980. percent = 'undefined' != typeof (prizes[i].weight) ? prizes[i].weight : 0;
  981. for (let j = 0; j < percent; j++) {
  982. index.push(i);
  983. }
  984. total += percent;
  985. }
  986. //随机数值
  987. let rand = Math.floor(Math.random() * total);
  988. return prizes[index[rand]];
  989. };
  990. /**
  991. * 更新用户信息
  992. * @date:2023/10/20
  993. */
  994. async updateUserInfo() {
  995. const that = this;
  996. try {
  997. const data = await that.ctx.validate(that.updateValidate, await that.ctx.anyParse());
  998. // 2023/10/20 更新用户信息
  999. const dataParam = {};
  1000. if (data.is_office) {
  1001. dataParam.is_office = true;
  1002. }
  1003. if (data.is_family) {
  1004. dataParam.is_family = true;
  1005. }
  1006. dataParam.update_ttime = that.app.szjcomo.date('Y-m-d H:i:s');
  1007. const updateBean = await that.app.comoBean.instance(dataParam, { where: { user_id: data.user_id } });
  1008. const result = await that.service.base.update(updateBean, that.useModel, '微信用户信息更新失败,请重试');
  1009. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  1010. } catch (e) {
  1011. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  1012. }
  1013. }
  1014. };