user.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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. couponCode: 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. // 2023/2/28 UIOT现金券发放
  243. that.service.coupon.dispatchCoupon(user.user_id);
  244. const token = that.app.jwt.sign(user, that.app.config.jwt.secret, { expiresIn: '24h' });
  245. const result = { token, user };
  246. return result;
  247. }
  248. /**
  249. * [register 用户注册]
  250. * @return {[type]} [description]
  251. */
  252. async register() {
  253. const that = this;
  254. try {
  255. const data = await that.ctx.validate(that.registerValidate, await that.ctx.postParse());
  256. const createBean = that.app.comoBean.instance(data, {});
  257. const result = await that.service.manager.create(createBean, that.useModel, '注册失败,请稍候重试');
  258. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  259. } catch (err) {
  260. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  261. }
  262. }
  263. /**
  264. * [wxRegisterAdnLogin 用户登录 - 微信注册登录]
  265. * @return {[type]} [description]
  266. */
  267. async wxRegisterAdnLogin() {
  268. const that = this;
  269. try {
  270. const appid = await that.service.configs.getConfigValue('wechat_account_appid');
  271. const secret = await that.service.configs.getConfigValue('wechat_account_secret');
  272. const data = await that.ctx.validate(that.wxRegisterAdnLoginValidate, await that.ctx.getParse());
  273. const result = await that.service.wechat.authLogin(appid, secret, data.code);
  274. if (result.errcode) throw new Error(`微信通讯失败,错误信息:${result.errmsg}`);
  275. const userInfo = await that.service.wechat.authUserInfo(result);
  276. const user = await that.wxRegisterAdnLoginHandle(userInfo, data.inviteCode);
  277. const loginRes = await that.loginHandle(user);
  278. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', loginRes, false));
  279. } catch (err) {
  280. await that.logs('user.js', err);
  281. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  282. }
  283. }
  284. /**
  285. * [wxloginURL 微信登录地址]
  286. * @return {[type]} [description]
  287. */
  288. async wxloginURL() {
  289. const that = this;
  290. try {
  291. const data = await that.ctx.validate(that.wxloginURLValidate, await that.ctx.postParse());
  292. const appid = await that.service.configs.getConfigValue('wechat_account_appid');
  293. const curarr = data.page_uri.split('#');
  294. 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`;
  295. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  296. } catch (err) {
  297. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  298. }
  299. }
  300. /**
  301. * [wxRegisterAdnLoginHandle 注册并登录]
  302. * @param {Object} userInfo [description]
  303. * @param {Number} inviteCode
  304. * @return {[type]} [description]
  305. */
  306. async wxRegisterAdnLoginHandle(userInfo = {}, inviteCode = -1) {
  307. const that = this;
  308. const inviter_id = inviteCode;
  309. // console.log('==========inviteCode========== : ' + inviter_id);
  310. const options = {
  311. where: { openid: userInfo.openid },
  312. attributes: [ 'user_id', 'account_name', 'nickname', 'headimgurl', 'openid', 'partner_id', 'is_office', 'is_family', 'lucky_time' ],
  313. raw: true,
  314. };
  315. let user = await that.useModel.findOne(options);
  316. if (!user) {
  317. // 2022/9/27 新用户注册 写入信息
  318. user = await that.writeWxUser(userInfo);
  319. user.isNew = true;
  320. // 2022/9/27: 新用户红包奖励8.8元
  321. await that.service.shop.userMoneyAdd(user.user_id, 8.8, null, '新用户注册奖励', 0, 1, -1);
  322. // 2022/9/29 受邀注册奖励 和 邀请新用户奖励
  323. if (inviter_id > 0) {
  324. try {
  325. const inviterInfo = await that.useModel.findOne({
  326. where: { user_id: inviter_id },
  327. attributes: [ 'user_id', 'nickname', 'headimgurl' ],
  328. raw: true,
  329. });
  330. await that.service.shop.userMoneyAdd(user.user_id, 1.68, null, '受邀注册奖励', 0, 2, inviter_id, inviterInfo.nickname, inviterInfo.headimgurl);
  331. await that.service.shop.userMoneyAdd(inviter_id, 1.68, null, '邀请新用户奖励', 0, 3, user.user_id, user.nickname, user.headimgurl);
  332. // 2022/11/17 邀请关系绑定
  333. await that.service.inviter.addRelUserInviter(user.user_id, inviter_id);
  334. } catch (e) {
  335. // 邀请人id不存在
  336. }
  337. }
  338. } else {
  339. user.isNew = false;
  340. // 2023/8/25 更新登录时间
  341. const updateBean = await that.app.comoBean.instance({
  342. login_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  343. update_ttime: that.app.szjcomo.date('Y-m-d H:i:s'),
  344. unionid: userInfo.unionid,
  345. }, { where: { user_id: user.user_id } });
  346. await that.service.base.update(updateBean, that.useModel, '微信用户登录时间更新失败,请重试');
  347. }
  348. return user;
  349. }
  350. /**
  351. * [writeWxUser 写入微信用户]
  352. * @param {Object} userInfo [description]
  353. * @return {[type]} [description]
  354. */
  355. async writeWxUser(userInfo = {}) {
  356. const that = this;
  357. const data = await that.ctx.validate(that.wxuserValidate, userInfo);
  358. const createBean = await that.app.comoBean.instance(data);
  359. const result = await that.service.base.create(createBean, that.useModel, '添加微信用户失败,请重试');
  360. return {
  361. user_id: result.dataValues.user_id,
  362. account_name: result.dataValues.account_name,
  363. nickname: result.dataValues.nickname,
  364. headimgurl: result.dataValues.headimgurl,
  365. openid: result.dataValues.openid,
  366. unionid: result.dataValues.unionid,
  367. is_office: result.dataValues.is_office,
  368. is_family: result.dataValues.is_family,
  369. };
  370. }
  371. /**
  372. * [userMoney 获取用户余额]
  373. * @return {[type]} [description]
  374. */
  375. async userMoney() {
  376. const that = this;
  377. try {
  378. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  379. const result = await that.service.shop.getUserMoney(data.user_id);
  380. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  381. } catch (err) {
  382. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  383. }
  384. }
  385. /**
  386. * [userMoney 获取用户账户余额]
  387. * @return {[type]} [description]
  388. */
  389. async userAccount() {
  390. const that = this;
  391. try {
  392. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  393. const result = await that.service.shop.getUserAccount(data.user_id);
  394. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  395. } catch (err) {
  396. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  397. }
  398. }
  399. /**
  400. * [userMoneyLog 用户资金明细]
  401. * @return {[type]} [description]
  402. */
  403. async userMoneyLog() {
  404. const that = this;
  405. try {
  406. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  407. const selectBean = await that.app.comoBean.instance(data, {
  408. offset: (data.page - 1) * data.limit,
  409. limit: data.limit,
  410. where: { user_id: data.user_id },
  411. order: [ [ 'log_id', 'desc' ] ],
  412. attributes: [ 'log_id', 'log_desc', 'change_time', 'money', 'type', 'inviter_id', 'inviter_name', 'inviter_img' ],
  413. });
  414. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '查询资金明细失败,请稍候重试', true, true);
  415. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  416. } catch (err) {
  417. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  418. }
  419. }
  420. /**
  421. * [userMoneyLog 用户分佣明细]
  422. * @return {[type]} [description]
  423. */
  424. async userCommissionLog() {
  425. const that = this;
  426. try {
  427. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  428. const selectBean = await that.app.comoBean.instance(data, {
  429. // offset: (data.page - 1) * data.limit, limit: data.limit,
  430. where: { user_id: data.user_id },
  431. order: [ [ 'log_id', 'desc' ] ],
  432. include: [ {
  433. model: that.app.model.Orders,
  434. attributes: [ 'order_id', 'order_status', 'order_amount', ],
  435. as: 'order'
  436. } ],
  437. attributes: [ 'log_desc', 'create_time', 'commission', 'type', 'inviter_id', 'inviter_name', 'inviter_img' ],
  438. });
  439. // 2022/11/28 直接查询所有数据 不分页
  440. const result = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询分佣明细失败,请稍候重试', false, true);
  441. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  442. } catch (err) {
  443. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  444. }
  445. }
  446. /**
  447. * [userMoneyLog 用户餐币明细]
  448. * @return {[type]} [description]
  449. */
  450. async coinDetail() {
  451. const that = this;
  452. try {
  453. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  454. const selectBean = await that.app.comoBean.instance(data, {
  455. where: { user_id: data.user_id },
  456. order: [ [ 'log_id', 'desc' ] ],
  457. });
  458. // 2022/11/28 直接查询所有数据 不分页
  459. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询分佣明细失败,请稍候重试', false, true);
  460. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  461. } catch (err) {
  462. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  463. }
  464. }
  465. // 2023/2/28 用户卡券账户列表
  466. async userCoupon() {
  467. const that = this;
  468. try {
  469. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  470. const selectBean = await that.app.comoBean.instance(data, {
  471. where: { user_id: data.user_id, expired: false },
  472. include: { model: that.app.model.PartnerInfo, as: 'partnerInfo', attributes: [ 'latitude', 'longitude' ] }
  473. });
  474. // 2023/2/28 直接查询所有数据 不分页
  475. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户失败,请稍候重试', false, true);
  476. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  477. } catch (err) {
  478. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  479. }
  480. }
  481. /**
  482. * 用户指定商家餐币账户余额
  483. * @return {Promise<*>}
  484. */
  485. async userCouldTransferCoin() {
  486. const that = this;
  487. try {
  488. const data = await that.ctx.validate(that.userTransferValidate, await that.ctx.getParse());
  489. const res = await that.getCouldTransferCoin(data);
  490. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', { couldTransferCoins: res.account }, false));
  491. } catch (err) {
  492. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  493. }
  494. }
  495. /**
  496. * 用户可在指定商家消费的餐币账户余额
  497. * @param data
  498. */
  499. async getCouldTransferCoin(data) {
  500. const that = this;
  501. if (!data.couponCode) {
  502. throw new Error('参数错误');
  503. }
  504. const userInfo = await that.app.model.Users.findOne({
  505. where: { openid: data.couponCode },
  506. attributes: [ 'user_id' ],
  507. });
  508. if (!userInfo || userInfo.user_id < 0) {
  509. throw new Error('参数错误');
  510. }
  511. const businessInfo = await that.app.model.Users.findOne({
  512. where: { user_id: data.user_id },
  513. attributes: [ 'partner_id' ],
  514. });
  515. if (!businessInfo || businessInfo.partner_id < 1) {
  516. throw new Error('抱歉,您没有核销卡券的权限!请联系管理员!');
  517. }
  518. const seq = that.app.Sequelize;
  519. const selectBean = await that.app.comoBean.instance({}, {
  520. where: {
  521. user_id: userInfo.user_id,
  522. // partner_id: businessInfo.partner_id,
  523. // 2023/4/11 补充通用餐币
  524. partner_id: { [seq.Op.in]: [ businessInfo.partner_id, 1 ] },
  525. expired: false,
  526. },
  527. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  528. });
  529. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询客户卡券账户失败,请稍候重试', false, false);
  530. const res = JSON.parse(JSON.stringify(result));
  531. res.customer_id = userInfo.user_id;
  532. res.partner_id = businessInfo.partner_id;
  533. res.business_id = data.user_id;
  534. return res;
  535. }
  536. /**
  537. * 商家可提现餐币金额
  538. * @return {Promise<*>}
  539. */
  540. async businessDiningCoinCouldCash() {
  541. const that = this;
  542. try {
  543. const data = await that.ctx.validate(that.businessCashCoinValidate, await that.ctx.getParse());
  544. const res = await that.getDiningCoinCouldCash(data);
  545. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', res, false));
  546. } catch (err) {
  547. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  548. }
  549. }
  550. /**
  551. * 商家可提现餐币金额
  552. * @param data
  553. */
  554. async getDiningCoinCouldCash(data) {
  555. const that = this;
  556. const businessInfo = await that.app.model.Users.findOne({
  557. where: { user_id: data.user_id },
  558. });
  559. if (!businessInfo || businessInfo.partner_id < 0) {
  560. throw new Error('您的账号还没有绑定的合作商铺哦');
  561. }
  562. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  563. where: { id: businessInfo.partner_id },
  564. });
  565. if (!partnerInfo || partnerInfo.user_id !== data.user_id) {
  566. throw new Error('您的账号没有权限提现餐费哦');
  567. }
  568. const seq = that.app.Sequelize;
  569. const currentDateTime = that.app.szjcomo.date('Y-m-d H:i:s');
  570. const sevenDayTime = 24 * 60 * 60 * 1000; // 2023/3/1 24小时后可提现
  571. const endTimeStamp = Date.parse(currentDateTime) - sevenDayTime;
  572. const endDateTime = that.app.szjcomo.date('Y-m-d H:i:s', endTimeStamp / 1000);
  573. // 2023/3/1 查询24小时前的所得餐币总和 以及所有时间提现的总和 再求和 即为 可提现餐币金额
  574. // todo : 特殊情况 商家管理员有自家绑定的商铺 餐币消费支出
  575. const selectBean = await that.app.comoBean.instance({}, {
  576. where: {
  577. user_id: businessInfo.user_id,
  578. partner_id: businessInfo.partner_id,
  579. create_time: { [seq.Op.lte]: endDateTime },
  580. account: { [seq.Op.gte]: 0 },
  581. },
  582. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  583. });
  584. const coinResult = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  585. const selectBean2 = await that.app.comoBean.instance({}, {
  586. where: {
  587. user_id: businessInfo.user_id,
  588. partner_id: businessInfo.partner_id,
  589. account: { [seq.Op.lte]: 0 },
  590. type: { [seq.Op.ne]: -1 },
  591. },
  592. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  593. });
  594. const cashResult = await that.service.base.select(selectBean2, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  595. const coinRes = JSON.parse(JSON.stringify(coinResult));
  596. const cashRes = JSON.parse(JSON.stringify(cashResult));
  597. const couldCash = new Decimal(coinRes.account ? coinRes.account : 0)
  598. .add(new Decimal(cashRes.account ? cashRes.account : 0))
  599. .toNumber();
  600. coinRes.all_coin_could_cash = couldCash > 0 ? couldCash : 0;
  601. coinRes.all_cash = cashRes.account;
  602. coinRes.partner_id = businessInfo.partner_id;
  603. coinRes.partner_fees = partnerInfo.partner_fees;
  604. return coinRes;
  605. }
  606. /**
  607. * 商家申请核销顾客卡券
  608. * @return {Promise<void>}
  609. */
  610. async coinTransfer() {
  611. const that = this;
  612. const seq = that.app.Sequelize;
  613. const transaction = await that.app.model.transaction();
  614. try {
  615. const data = await that.ctx.validate(that.coinTransferValidate, await that.ctx.postParse());
  616. // 2023/2/28 获取可核销餐币
  617. const intervalTime = Date.parse(that.app.szjcomo.date('Y-m-d H:i:s')) - data.time;
  618. if (intervalTime > 10 * 60 * 1000) {
  619. throw new Error('顾客卡券二维码已超时失效,请重新扫码!');
  620. }
  621. const transferParams = await that.getCouldTransferCoin(data);
  622. if (data.coinAmount > 0 && data.coinAmount <= transferParams.account) {
  623. // 2023/2/28 核销卡券的商家信息
  624. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  625. where: { id: transferParams.partner_id },
  626. });
  627. // 2024/9/13 被核销用户卡券信息
  628. const result = await that.app.model.DinnerCoins.findOne({
  629. where: {
  630. user_id: transferParams.customer_id,
  631. // partner_id: transferParams.partner_id,
  632. partner_id: { [seq.Op.in]: [ transferParams.partner_id, 1 ] },
  633. expired: false,
  634. }
  635. });
  636. if (result) {
  637. // 2024/9/13 核销 更新顾客账户
  638. const customerAccountBean = await that.app.comoBean.instance({
  639. expired: true,
  640. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  641. expired_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  642. }, {
  643. where: {
  644. user_id: transferParams.customer_id,
  645. partner_id: transferParams.partner_id,
  646. expired: false,
  647. }, transaction,
  648. });
  649. await that.service.base.update(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币余额更新失败,请重试');
  650. } else {
  651. throw new Error('当前客户没有符合条件的卡券或者卡券已过期!');
  652. }
  653. await transaction.commit();
  654. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', {
  655. expired: true,
  656. }, false));
  657. }
  658. throw new Error('输入的核销金额有误,请稍后重试');
  659. } catch (e) {
  660. if (transaction) transaction.rollback();
  661. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  662. }
  663. }
  664. // 2023/3/1 餐币划账 具体逻辑和操作
  665. async doTransferCoins(that, transferParams, coinAmount, partnerInfo, transaction, customerAccounts, index) {
  666. // 2023/3/6 获取顾客信息
  667. const customerInfo = await that.app.model.Users.findOne({
  668. where: { user_id: transferParams.customer_id },
  669. transaction,
  670. raw: true,
  671. });
  672. // 2023/3/1 扣去顾客餐币
  673. await that.service.diningCoin.addDiningCoinChangeLog({
  674. user_id: transferParams.customer_id,
  675. order_id: -1,
  676. partner_id: customerAccounts[index].partner_id,
  677. type: 3,
  678. account: -coinAmount,
  679. log_desc: partnerInfo.name + ' 消费',
  680. }, transaction);
  681. // 2023/3/1 更新顾客账户
  682. const customerAccountBean = await that.app.comoBean.instance({
  683. account: customerAccounts[index].account - coinAmount,
  684. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  685. }, {
  686. where: {
  687. user_id: transferParams.customer_id,
  688. ori_partner: customerAccounts[index].ori_partner,
  689. partner_id: customerAccounts[index].partner_id,
  690. expired: false,
  691. }, transaction,
  692. });
  693. if (customerAccounts[index].account === coinAmount) {
  694. // 2023/3/1 删除0元账户
  695. await that.service.base.delete(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币清零更新失败,请重试');
  696. } else {
  697. await that.service.base.update(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币余额更新失败,请重试');
  698. }
  699. // 2023/3/1 划入商家账户记录
  700. const businessCoinAmount = coinAmount * (customerAccounts[index].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  701. await that.service.diningCoin.addDiningCoinChangeLog({
  702. user_id: transferParams.business_id,
  703. order_id: -1,
  704. partner_id: transferParams.partner_id,
  705. type: 4,
  706. account: businessCoinAmount,
  707. log_desc: '核销收取餐币',
  708. ori_partner: customerAccounts[index].ori_partner,
  709. customer_id: customerInfo.user_id,
  710. customer_name: customerInfo.nickname,
  711. customer_img: customerInfo.headimgurl,
  712. }, transaction);
  713. // 2023/2/28 查询商家餐饮币账户列表 添加 或 更新账户余额
  714. const info = await that.app.model.DinnerCoins.findOne({
  715. where: {
  716. user_id: transferParams.business_id,
  717. // ori_partner: customerAccounts[index].ori_partner,
  718. partner_id: transferParams.partner_id,
  719. expired: false,
  720. },
  721. transaction,
  722. raw: true,
  723. });
  724. if (!info) {
  725. // 2023/2/27 没有对应类型的餐饮币 则插入该类型的餐饮币账户
  726. const createData = {
  727. user_id: transferParams.business_id,
  728. account: businessCoinAmount,
  729. // ori_partner: customerAccounts[index].ori_partner,
  730. ori_partner: true,
  731. partner_id: transferParams.partner_id,
  732. create_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  733. expired: false,
  734. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  735. };
  736. createData.partner_name = partnerInfo.name;
  737. createData.partner_address = partnerInfo.address;
  738. createData.partner_tel = partnerInfo.tel_num;
  739. createData.partner_opening_time = partnerInfo.opening_time;
  740. const createBean = await that.app.comoBean.instance(createData, { transaction });
  741. await that.service.base.create(createBean, that.app.model.DinnerCoins, '餐饮币发放失败,请重试');
  742. } else {
  743. const updateBean = await that.app.comoBean.instance({
  744. account: info.account + businessCoinAmount,
  745. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  746. expired: false,
  747. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  748. }, {
  749. where: {
  750. user_id: transferParams.business_id,
  751. // ori_partner: customerAccounts[index].ori_partner,
  752. partner_id: transferParams.partner_id,
  753. }, transaction,
  754. });
  755. await that.service.base.update(updateBean, that.app.model.DinnerCoins, '餐饮币余额更新失败,请重试');
  756. }
  757. }
  758. /**
  759. * 用户可提现金额(求和)
  760. * @return {Promise<*>}
  761. */
  762. async userCommissionCouldCash() {
  763. const that = this;
  764. try {
  765. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  766. const result = await that.getCouldCashCommission(data.user_id);
  767. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  768. } catch (err) {
  769. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  770. }
  771. }
  772. /**
  773. * 获取用户可提现金额(求和)
  774. * @return {Promise<void>}
  775. */
  776. async getCouldCashCommission(user_id = -1) {
  777. if (user_id <= 0) {
  778. throw new Error('参数错误');
  779. }
  780. const that = this;
  781. const seq = that.app.Sequelize;
  782. // 2024/2/26 所有分佣金额
  783. const selectBean = await that.app.comoBean.instance({ user_id }, {
  784. where: { user_id, commission: { [seq.Op.gte]: 0 } },
  785. include: [ {
  786. model: that.app.model.Orders,
  787. where: { order_status: { [seq.Op.in]: [ 1, 2, 3, 4 ] } },
  788. attributes: [ 'order_id', 'order_status', 'order_amount', ],
  789. as: 'order'
  790. } ],
  791. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_commission' ] ],
  792. });
  793. const allCommissionResult = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  794. // 2024/2/26 订单完成可提现金额
  795. const selectBean3 = await that.app.comoBean.instance({ user_id }, {
  796. where: { user_id, commission: { [seq.Op.gte]: 0 } },
  797. include: [ {
  798. model: that.app.model.Orders,
  799. where: { order_status: { [seq.Op.in]: [ 3, 4 ] } },
  800. attributes: [ 'order_id', 'order_status', 'order_amount', ],
  801. as: 'order'
  802. } ],
  803. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'order_done_commission' ] ],
  804. });
  805. const orderCommissionResult = await that.service.base.select(selectBean3, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  806. // 2024/2/26 已提现金额
  807. const selectBean2 = await that.app.comoBean.instance({ user_id }, {
  808. where: { user_id, commission: { [seq.Op.lte]: 0 }, type: { [seq.Op.ne]: -1 } }, // type-1提现失败类型
  809. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_cash' ] ],
  810. });
  811. const cashResult = await that.service.base.select(selectBean2, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  812. const allCommRes = JSON.parse(JSON.stringify(allCommissionResult));
  813. const orderCommRes = JSON.parse(JSON.stringify(orderCommissionResult));
  814. const cashRes = JSON.parse(JSON.stringify(cashResult));
  815. // 2024/2/26 待提现分佣金额
  816. cashRes.all_commission_tobe_cash = new Decimal(allCommRes.all_commission ? allCommRes.all_commission : 0)
  817. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  818. .toNumber();
  819. // 2024/2/26 可提现分佣金额
  820. cashRes.all_commission_could_cash = new Decimal(orderCommRes.order_done_commission ? orderCommRes.order_done_commission : 0)
  821. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  822. .toNumber();
  823. cashRes.all_commission = allCommRes.all_commission;
  824. // 2024/2/26 待订单确认收货分佣
  825. cashRes.all_commission_order_not_done = new Decimal(allCommRes.all_commission ? allCommRes.all_commission : 0)
  826. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  827. .sub(cashRes.all_commission_could_cash)
  828. .toNumber();
  829. return cashRes;
  830. }
  831. /**
  832. * 用户佣金提现
  833. * @return {Promise<void>}
  834. */
  835. async userCashOut() {
  836. const that = this;
  837. try {
  838. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  839. // 2023/1/17 获取可提现佣金额度
  840. const res = await that.getCouldCashCommission(data.user_id);
  841. if (data.cash_amount >= 0.1 && data.cash_amount <= res.all_commission_could_cash) {
  842. // 2023/1/31 发起提现
  843. const result = await that.service.wxPay.transfer(data);
  844. // 2023/1/31 提现状态
  845. if (result.status != 200) {
  846. throw new Error('提现转账出现异常,请联系客服后再重试');
  847. }
  848. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  849. }
  850. throw new Error('输入提现金额有误,请稍后重试');
  851. } catch (e) {
  852. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  853. }
  854. }
  855. /**
  856. * 用户佣金转电子餐费
  857. * @return {Promise<void>}
  858. */
  859. async commission2DiningCoin() {
  860. // 2023/11/17 todo: 佣金转电子餐费
  861. }
  862. /**
  863. * 商家餐币提现
  864. * @return {Promise<*>}
  865. */
  866. async userCoinCashOut() {
  867. const that = this;
  868. try {
  869. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  870. // 2023/1/17 获取可提现佣金额度
  871. const res = await that.getDiningCoinCouldCash(data);
  872. data.partner_id = res.partner_id;
  873. if (data.cash_amount >= 0.1 && data.cash_amount <= (res.all_coin_could_cash - res.partner_fees)) {
  874. // 2023/1/31 发起提现
  875. const result = await that.service.businessPayService.transfer(data);
  876. // 2023/1/31 提现状态
  877. if (result.status != 200) {
  878. throw new Error('提现转账出现异常,请联系客服后再重试');
  879. }
  880. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  881. }
  882. throw new Error('输入提现金额有误,请稍后重试');
  883. } catch (e) {
  884. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  885. }
  886. }
  887. /**
  888. * [newUserBenefits 查询新用户福利]
  889. * @return {[type]} [description]
  890. */
  891. async newUserBenefits() {
  892. const that = this;
  893. try {
  894. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  895. const seq = that.app.Sequelize;
  896. const selectBean = await that.app.comoBean.instance(data, {
  897. offset: (data.page - 1) * data.limit, limit: data.limit, where: {
  898. user_id: data.user_id,
  899. type: { [seq.Op.in]: [ 1, 2 ] },
  900. },
  901. order: [ [ 'type', 'asc' ] ],
  902. });
  903. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '新用户福利查询失败,请稍候重试', true, true);
  904. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  905. } catch (err) {
  906. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  907. }
  908. }
  909. /**
  910. * [newUserBenefits 获取每日红包]
  911. * @return {[type]} [description]
  912. */
  913. async dayLucky() {
  914. const that = this;
  915. try {
  916. const data = await that.ctx.validate(that.luckyValidate, await that.ctx.anyParse());
  917. // 2023/11/17 用户今天是否已经抽奖
  918. const user = await that.useModel.findOne({
  919. where: { user_id: data.user_id },
  920. });
  921. const isTodayLucky = await that.service.baseUtils.isToday(user.lucky_time);
  922. // const isTodayLucky = false;
  923. if (isTodayLucky) {
  924. throw new Error('您今天已经抽奖了哦,明天再来吧!');
  925. } else {
  926. // 2023/11/17 : 发起概率抽奖 发放奖项 (红包上限)
  927. let prizes;
  928. if (user.money > 999) {
  929. prizes = [
  930. { reward: 6, weight: 1 },
  931. { reward: 1, weight: 95 },
  932. { reward: 10, weight: 1 },
  933. { reward: 8, weight: 1 },
  934. { reward: 30, weight: 1 },
  935. { reward: 20, weight: 1 }
  936. ];
  937. } else {
  938. prizes = [
  939. { reward: 6, weight: 4 },
  940. { reward: 1, weight: 1 },
  941. { reward: 10, weight: 50 },
  942. { reward: 8, weight: 10 },
  943. { reward: 30, weight: 5 },
  944. { reward: 20, weight: 30 }
  945. ];
  946. }
  947. const prizeAward = await that.lottery(prizes);
  948. // 2023/11/21 发放红包奖励
  949. // console.log(prizeAward);
  950. await that.service.shop.userMoneyAdd(user.user_id, prizeAward.reward, null, '每日抽奖红包', 0, 4);
  951. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', prizeAward, false));
  952. }
  953. } catch (err) {
  954. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  955. }
  956. }
  957. //权重抽奖函数
  958. async lottery(prizes) {
  959. let total = 0;
  960. let percent;
  961. //下标标记数组
  962. let index = [];
  963. for (let i = 0; i < prizes.length; i++) {
  964. //判断元素的权重,为了实现小数权重,先将所有的值放大100倍
  965. percent = 'undefined' != typeof (prizes[i].weight) ? prizes[i].weight : 0;
  966. for (let j = 0; j < percent; j++) {
  967. index.push(i);
  968. }
  969. total += percent;
  970. }
  971. //随机数值
  972. let rand = Math.floor(Math.random() * total);
  973. return prizes[index[rand]];
  974. };
  975. /**
  976. * 更新用户信息
  977. * @date:2023/10/20
  978. */
  979. async updateUserInfo() {
  980. const that = this;
  981. try {
  982. const data = await that.ctx.validate(that.updateValidate, await that.ctx.anyParse());
  983. // 2023/10/20 更新用户信息
  984. const dataParam = {};
  985. if (data.is_office) {
  986. dataParam.is_office = true;
  987. }
  988. if (data.is_family) {
  989. dataParam.is_family = true;
  990. }
  991. dataParam.update_ttime = that.app.szjcomo.date('Y-m-d H:i:s');
  992. const updateBean = await that.app.comoBean.instance(dataParam, { where: { user_id: data.user_id } });
  993. const result = await that.service.base.update(updateBean, that.useModel, '微信用户信息更新失败,请重试');
  994. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  995. } catch (e) {
  996. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  997. }
  998. }
  999. };