user.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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. include: [ {
  431. model: that.app.model.Orders,
  432. attributes: [ 'order_id', 'order_status', 'order_amount', ],
  433. as: 'order'
  434. } ],
  435. attributes: [ 'log_desc', 'create_time', 'commission', 'type', 'inviter_id', 'inviter_name', 'inviter_img' ],
  436. });
  437. // 2022/11/28 直接查询所有数据 不分页
  438. const result = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询分佣明细失败,请稍候重试', false, true);
  439. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  440. } catch (err) {
  441. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  442. }
  443. }
  444. /**
  445. * [userMoneyLog 用户餐币明细]
  446. * @return {[type]} [description]
  447. */
  448. async coinDetail() {
  449. const that = this;
  450. try {
  451. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  452. const selectBean = await that.app.comoBean.instance(data, {
  453. where: { user_id: data.user_id },
  454. order: [ [ 'log_id', 'desc' ] ],
  455. });
  456. // 2022/11/28 直接查询所有数据 不分页
  457. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询分佣明细失败,请稍候重试', false, true);
  458. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  459. } catch (err) {
  460. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  461. }
  462. }
  463. // 2023/2/28 用户餐饮币账户列表
  464. async userDiningCoin() {
  465. const that = this;
  466. try {
  467. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  468. const selectBean = await that.app.comoBean.instance(data, {
  469. where: { user_id: data.user_id, expired: false },
  470. });
  471. // 2023/2/28 直接查询所有数据 不分页
  472. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户失败,请稍候重试', false, true);
  473. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  474. } catch (err) {
  475. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  476. }
  477. }
  478. /**
  479. * 用户指定商家餐币账户余额
  480. * @return {Promise<*>}
  481. */
  482. async userCouldTransferCoin() {
  483. const that = this;
  484. try {
  485. const data = await that.ctx.validate(that.userTransferValidate, await that.ctx.getParse());
  486. const res = await that.getCouldTransferCoin(data);
  487. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', { couldTransferCoins: res.account }, false));
  488. } catch (err) {
  489. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  490. }
  491. }
  492. /**
  493. * 用户可在指定商家消费的餐币账户余额
  494. * @param data
  495. */
  496. async getCouldTransferCoin(data) {
  497. const that = this;
  498. if (!data.diningCoinCode) {
  499. throw new Error('参数错误');
  500. }
  501. const userInfo = await that.app.model.Users.findOne({
  502. where: { openid: data.diningCoinCode },
  503. attributes: [ 'user_id' ],
  504. });
  505. if (!userInfo || userInfo.user_id < 0) {
  506. throw new Error('参数错误');
  507. }
  508. const businessInfo = await that.app.model.Users.findOne({
  509. where: { user_id: data.user_id },
  510. attributes: [ 'partner_id' ],
  511. });
  512. if (!businessInfo || businessInfo.partner_id < 1) {
  513. throw new Error('抱歉,您不是源森家具的合作商户,无权收款。');
  514. }
  515. const seq = that.app.Sequelize;
  516. const selectBean = await that.app.comoBean.instance({}, {
  517. where: {
  518. user_id: userInfo.user_id,
  519. // partner_id: businessInfo.partner_id,
  520. // 2023/4/11 补充通用餐币
  521. partner_id: { [seq.Op.in]: [ businessInfo.partner_id, 1 ] },
  522. expired: false,
  523. },
  524. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  525. });
  526. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户余额失败,请稍候重试', false, false);
  527. const res = JSON.parse(JSON.stringify(result));
  528. res.customer_id = userInfo.user_id;
  529. res.partner_id = businessInfo.partner_id;
  530. res.business_id = data.user_id;
  531. return res;
  532. }
  533. /**
  534. * 商家可提现餐币金额
  535. * @return {Promise<*>}
  536. */
  537. async businessDiningCoinCouldCash() {
  538. const that = this;
  539. try {
  540. const data = await that.ctx.validate(that.businessCashCoinValidate, await that.ctx.getParse());
  541. const res = await that.getDiningCoinCouldCash(data);
  542. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', res, false));
  543. } catch (err) {
  544. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  545. }
  546. }
  547. /**
  548. * 商家可提现餐币金额
  549. * @param data
  550. */
  551. async getDiningCoinCouldCash(data) {
  552. const that = this;
  553. const businessInfo = await that.app.model.Users.findOne({
  554. where: { user_id: data.user_id },
  555. });
  556. if (!businessInfo || businessInfo.partner_id < 0) {
  557. throw new Error('您的账号还没有绑定的合作商铺哦');
  558. }
  559. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  560. where: { id: businessInfo.partner_id },
  561. });
  562. if (!partnerInfo || partnerInfo.user_id !== data.user_id) {
  563. throw new Error('您的账号没有权限提现餐费哦');
  564. }
  565. const seq = that.app.Sequelize;
  566. const currentDateTime = that.app.szjcomo.date('Y-m-d H:i:s');
  567. const sevenDayTime = 24 * 60 * 60 * 1000; // 2023/3/1 24小时后可提现
  568. const endTimeStamp = Date.parse(currentDateTime) - sevenDayTime;
  569. const endDateTime = that.app.szjcomo.date('Y-m-d H:i:s', endTimeStamp / 1000);
  570. // 2023/3/1 查询24小时前的所得餐币总和 以及所有时间提现的总和 再求和 即为 可提现餐币金额
  571. // todo : 特殊情况 商家管理员有自家绑定的商铺 餐币消费支出
  572. const selectBean = await that.app.comoBean.instance({}, {
  573. where: {
  574. user_id: businessInfo.user_id,
  575. partner_id: businessInfo.partner_id,
  576. create_time: { [seq.Op.lte]: endDateTime },
  577. account: { [seq.Op.gte]: 0 },
  578. },
  579. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  580. });
  581. const coinResult = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  582. const selectBean2 = await that.app.comoBean.instance({}, {
  583. where: {
  584. user_id: businessInfo.user_id,
  585. partner_id: businessInfo.partner_id,
  586. account: { [seq.Op.lte]: 0 },
  587. type: { [seq.Op.ne]: -1 },
  588. },
  589. attributes: [ [ seq.fn('sum', seq.col('account')), 'account' ] ],
  590. });
  591. const cashResult = await that.service.base.select(selectBean2, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  592. const coinRes = JSON.parse(JSON.stringify(coinResult));
  593. const cashRes = JSON.parse(JSON.stringify(cashResult));
  594. const couldCash = new Decimal(coinRes.account ? coinRes.account : 0)
  595. .add(new Decimal(cashRes.account ? cashRes.account : 0))
  596. .toNumber();
  597. coinRes.all_coin_could_cash = couldCash > 0 ? couldCash : 0;
  598. coinRes.all_cash = cashRes.account;
  599. coinRes.partner_id = businessInfo.partner_id;
  600. coinRes.partner_fees = partnerInfo.partner_fees;
  601. return coinRes;
  602. }
  603. /**
  604. * 商家申请核销餐币
  605. * @return {Promise<void>}
  606. */
  607. async coinTransfer() {
  608. const that = this;
  609. const seq = that.app.Sequelize;
  610. const transaction = await that.app.model.transaction();
  611. try {
  612. const data = await that.ctx.validate(that.coinTransferValidate, await that.ctx.postParse());
  613. // 2023/2/28 获取可核销餐币
  614. const intervalTime = Date.parse(that.app.szjcomo.date('Y-m-d H:i:s')) - data.time;
  615. if (intervalTime > 10 * 60 * 1000) {
  616. throw new Error('顾客付款码已超时失效,请重新扫码!');
  617. }
  618. const transferParams = await that.getCouldTransferCoin(data);
  619. if (data.coinAmount > 0 && data.coinAmount <= transferParams.account) {
  620. // 2023/2/28 发起核销收取餐币
  621. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  622. where: { id: transferParams.partner_id },
  623. });
  624. // 2023/4/12 核销餐币 包含通用电子餐币
  625. const selectBean = await that.app.comoBean.instance({}, {
  626. where: {
  627. user_id: transferParams.customer_id,
  628. // partner_id: transferParams.partner_id,
  629. partner_id: { [seq.Op.in]: [ transferParams.partner_id, 1 ] },
  630. expired: false,
  631. },
  632. order: [ [ 'partner_id', 'desc' ], [ 'ori_partner', 'desc' ] ],
  633. });
  634. // 2023/2/28 查询所有指定商家餐币
  635. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户失败,请稍候重试', false, true);
  636. const customerAccounts = [];
  637. let needAccount = 0;
  638. for (const resultElement of result) {
  639. needAccount += resultElement.account;
  640. customerAccounts.push(JSON.parse(JSON.stringify(resultElement)));
  641. if (needAccount >= data.coinAmount) {
  642. break;
  643. }
  644. }
  645. let firstCoinAmount;
  646. let secondCoinAmount;
  647. let thirdCoinAmount;
  648. let fourthCoinAmount;
  649. let incomeCoinAmount = 0;
  650. switch (customerAccounts.length) {
  651. case 1:
  652. firstCoinAmount = data.coinAmount;
  653. secondCoinAmount = 0;
  654. thirdCoinAmount = 0;
  655. fourthCoinAmount = 0;
  656. break;
  657. case 2:
  658. firstCoinAmount = customerAccounts[0].account;
  659. secondCoinAmount = data.coinAmount - firstCoinAmount;
  660. thirdCoinAmount = 0;
  661. fourthCoinAmount = 0;
  662. break;
  663. case 3:
  664. firstCoinAmount = customerAccounts[0].account;
  665. secondCoinAmount = customerAccounts[1].account;
  666. thirdCoinAmount = data.coinAmount - firstCoinAmount - secondCoinAmount;
  667. fourthCoinAmount = 0;
  668. break;
  669. case 4:
  670. firstCoinAmount = customerAccounts[0].account;
  671. secondCoinAmount = customerAccounts[1].account;
  672. thirdCoinAmount = customerAccounts[2].account;
  673. fourthCoinAmount = data.coinAmount - firstCoinAmount - secondCoinAmount - thirdCoinAmount;
  674. break;
  675. default:
  676. break;
  677. }
  678. // =========================================== 2023/3/1 第一个账户划账======================================
  679. await that.doTransferCoins(that, transferParams, firstCoinAmount, partnerInfo, transaction, customerAccounts, 0);
  680. incomeCoinAmount += firstCoinAmount * (customerAccounts[0].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  681. // =============================== 2023/3/1 需要第二个账户来继续划账 ==========================================
  682. if (customerAccounts.length > 1 && secondCoinAmount > 0) {
  683. await that.doTransferCoins(that, transferParams, secondCoinAmount, partnerInfo, transaction, customerAccounts, 1);
  684. incomeCoinAmount += secondCoinAmount * (customerAccounts[1].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  685. }
  686. // =============================== 2023/3/18 需要第三个账户来继续划账 ==========================================
  687. if (customerAccounts.length > 2 && thirdCoinAmount > 0) {
  688. await that.doTransferCoins(that, transferParams, thirdCoinAmount, partnerInfo, transaction, customerAccounts, 2);
  689. incomeCoinAmount += thirdCoinAmount * (customerAccounts[2].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  690. }
  691. // =============================== 2023/3/18 需要第四个账户来继续划账 ==========================================
  692. if (customerAccounts.length > 3 && fourthCoinAmount > 0) {
  693. await that.doTransferCoins(that, transferParams, fourthCoinAmount, partnerInfo, transaction, customerAccounts, 3);
  694. incomeCoinAmount += fourthCoinAmount * (customerAccounts[3].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  695. }
  696. await transaction.commit();
  697. incomeCoinAmount = incomeCoinAmount.toFixed(2);
  698. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', {
  699. incomeCoinAmount,
  700. transferCoinAmount: data.coinAmount,
  701. }, false));
  702. }
  703. throw new Error('输入的核销金额有误,请稍后重试');
  704. } catch (e) {
  705. if (transaction) transaction.rollback();
  706. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  707. }
  708. }
  709. // 2023/3/1 餐币划账 具体逻辑和操作
  710. async doTransferCoins(that, transferParams, coinAmount, partnerInfo, transaction, customerAccounts, index) {
  711. // 2023/3/6 获取顾客信息
  712. const customerInfo = await that.app.model.Users.findOne({
  713. where: { user_id: transferParams.customer_id },
  714. transaction,
  715. raw: true,
  716. });
  717. // 2023/3/1 扣去顾客餐币
  718. await that.service.diningCoin.addDiningCoinChangeLog({
  719. user_id: transferParams.customer_id,
  720. order_id: -1,
  721. partner_id: customerAccounts[index].partner_id,
  722. type: 3,
  723. account: -coinAmount,
  724. log_desc: partnerInfo.name + ' 消费',
  725. }, transaction);
  726. // 2023/3/1 更新顾客账户
  727. const customerAccountBean = await that.app.comoBean.instance({
  728. account: customerAccounts[index].account - coinAmount,
  729. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  730. }, {
  731. where: {
  732. user_id: transferParams.customer_id,
  733. ori_partner: customerAccounts[index].ori_partner,
  734. partner_id: customerAccounts[index].partner_id,
  735. expired: false,
  736. }, transaction,
  737. });
  738. if (customerAccounts[index].account === coinAmount) {
  739. // 2023/3/1 删除0元账户
  740. await that.service.base.delete(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币清零更新失败,请重试');
  741. } else {
  742. await that.service.base.update(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币余额更新失败,请重试');
  743. }
  744. // 2023/3/1 划入商家账户记录
  745. const businessCoinAmount = coinAmount * (customerAccounts[index].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  746. await that.service.diningCoin.addDiningCoinChangeLog({
  747. user_id: transferParams.business_id,
  748. order_id: -1,
  749. partner_id: transferParams.partner_id,
  750. type: 4,
  751. account: businessCoinAmount,
  752. log_desc: '核销收取餐币',
  753. ori_partner: customerAccounts[index].ori_partner,
  754. customer_id: customerInfo.user_id,
  755. customer_name: customerInfo.nickname,
  756. customer_img: customerInfo.headimgurl,
  757. }, transaction);
  758. // 2023/2/28 查询商家餐饮币账户列表 添加 或 更新账户余额
  759. const info = await that.app.model.DinnerCoins.findOne({
  760. where: {
  761. user_id: transferParams.business_id,
  762. // ori_partner: customerAccounts[index].ori_partner,
  763. partner_id: transferParams.partner_id,
  764. expired: false,
  765. },
  766. transaction,
  767. raw: true,
  768. });
  769. if (!info) {
  770. // 2023/2/27 没有对应类型的餐饮币 则插入该类型的餐饮币账户
  771. const createData = {
  772. user_id: transferParams.business_id,
  773. account: businessCoinAmount,
  774. // ori_partner: customerAccounts[index].ori_partner,
  775. ori_partner: true,
  776. partner_id: transferParams.partner_id,
  777. create_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  778. expired: false,
  779. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  780. };
  781. createData.partner_name = partnerInfo.name;
  782. createData.partner_address = partnerInfo.address;
  783. createData.partner_tel = partnerInfo.tel_num;
  784. createData.partner_opening_time = partnerInfo.opening_time;
  785. const createBean = await that.app.comoBean.instance(createData, { transaction });
  786. await that.service.base.create(createBean, that.app.model.DinnerCoins, '餐饮币发放失败,请重试');
  787. } else {
  788. const updateBean = await that.app.comoBean.instance({
  789. account: info.account + businessCoinAmount,
  790. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  791. expired: false,
  792. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  793. }, {
  794. where: {
  795. user_id: transferParams.business_id,
  796. // ori_partner: customerAccounts[index].ori_partner,
  797. partner_id: transferParams.partner_id,
  798. }, transaction,
  799. });
  800. await that.service.base.update(updateBean, that.app.model.DinnerCoins, '餐饮币余额更新失败,请重试');
  801. }
  802. }
  803. /**
  804. * 用户可提现金额(求和)
  805. * @return {Promise<*>}
  806. */
  807. async userCommissionCouldCash() {
  808. const that = this;
  809. try {
  810. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  811. const result = await that.getCouldCashCommission(data.user_id);
  812. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  813. } catch (err) {
  814. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  815. }
  816. }
  817. /**
  818. * 获取用户可提现金额(求和)
  819. * @return {Promise<void>}
  820. */
  821. async getCouldCashCommission(user_id = -1) {
  822. if (user_id <= 0) {
  823. throw new Error('参数错误');
  824. }
  825. const that = this;
  826. const seq = that.app.Sequelize;
  827. // 2024/2/26 所有分佣金额
  828. const selectBean = await that.app.comoBean.instance({ user_id }, {
  829. where: { user_id, commission: { [seq.Op.gte]: 0 } },
  830. include: [ {
  831. model: that.app.model.Orders,
  832. where: { order_status: { [seq.Op.in]: [ 1, 2, 3, 4 ] } },
  833. attributes: [ 'order_id', 'order_status', 'order_amount', ],
  834. as: 'order'
  835. } ],
  836. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_commission' ] ],
  837. });
  838. const allCommissionResult = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  839. // 2024/2/26 订单完成可提现金额
  840. const selectBean3 = await that.app.comoBean.instance({ user_id }, {
  841. where: { user_id, commission: { [seq.Op.gte]: 0 } },
  842. include: [ {
  843. model: that.app.model.Orders,
  844. where: { order_status: { [seq.Op.in]: [ 3, 4 ] } },
  845. attributes: [ 'order_id', 'order_status', 'order_amount', ],
  846. as: 'order'
  847. } ],
  848. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'order_done_commission' ] ],
  849. });
  850. const orderCommissionResult = await that.service.base.select(selectBean3, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  851. // 2024/2/26 已提现金额
  852. const selectBean2 = await that.app.comoBean.instance({ user_id }, {
  853. where: { user_id, commission: { [seq.Op.lte]: 0 }, type: { [seq.Op.ne]: -1 } }, // type-1提现失败类型
  854. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_cash' ] ],
  855. });
  856. const cashResult = await that.service.base.select(selectBean2, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  857. const allCommRes = JSON.parse(JSON.stringify(allCommissionResult));
  858. const orderCommRes = JSON.parse(JSON.stringify(orderCommissionResult));
  859. const cashRes = JSON.parse(JSON.stringify(cashResult));
  860. // 2024/2/26 待提现分佣金额
  861. cashRes.all_commission_tobe_cash = new Decimal(allCommRes.all_commission ? allCommRes.all_commission : 0)
  862. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  863. .toNumber();
  864. // 2024/2/26 可提现分佣金额
  865. cashRes.all_commission_could_cash = new Decimal(orderCommRes.order_done_commission ? orderCommRes.order_done_commission : 0)
  866. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  867. .toNumber();
  868. cashRes.all_commission = allCommRes.all_commission;
  869. // 2024/2/26 待订单确认收货分佣
  870. cashRes.all_commission_order_not_done = new Decimal(allCommRes.all_commission ? allCommRes.all_commission : 0)
  871. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  872. .sub(cashRes.all_commission_could_cash)
  873. .toNumber();
  874. return cashRes;
  875. }
  876. /**
  877. * 用户佣金提现
  878. * @return {Promise<void>}
  879. */
  880. async userCashOut() {
  881. const that = this;
  882. try {
  883. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  884. // 2023/1/17 获取可提现佣金额度
  885. const res = await that.getCouldCashCommission(data.user_id);
  886. if (data.cash_amount >= 0.1 && data.cash_amount <= res.all_commission_could_cash) {
  887. // 2023/1/31 发起提现
  888. const result = await that.service.wxPay.transfer(data);
  889. // 2023/1/31 提现状态
  890. if (result.status != 200) {
  891. throw new Error('提现转账出现异常,请联系客服后再重试');
  892. }
  893. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  894. }
  895. throw new Error('输入提现金额有误,请稍后重试');
  896. } catch (e) {
  897. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  898. }
  899. }
  900. /**
  901. * 用户佣金转电子餐费
  902. * @return {Promise<void>}
  903. */
  904. async commission2DiningCoin() {
  905. // 2023/11/17 todo: 佣金转电子餐费
  906. }
  907. /**
  908. * 商家餐币提现
  909. * @return {Promise<*>}
  910. */
  911. async userCoinCashOut() {
  912. const that = this;
  913. try {
  914. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  915. // 2023/1/17 获取可提现佣金额度
  916. const res = await that.getDiningCoinCouldCash(data);
  917. data.partner_id = res.partner_id;
  918. if (data.cash_amount >= 0.1 && data.cash_amount <= (res.all_coin_could_cash - res.partner_fees)) {
  919. // 2023/1/31 发起提现
  920. const result = await that.service.businessPayService.transfer(data);
  921. // 2023/1/31 提现状态
  922. if (result.status != 200) {
  923. throw new Error('提现转账出现异常,请联系客服后再重试');
  924. }
  925. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  926. }
  927. throw new Error('输入提现金额有误,请稍后重试');
  928. } catch (e) {
  929. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  930. }
  931. }
  932. /**
  933. * [newUserBenefits 查询新用户福利]
  934. * @return {[type]} [description]
  935. */
  936. async newUserBenefits() {
  937. const that = this;
  938. try {
  939. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  940. const seq = that.app.Sequelize;
  941. const selectBean = await that.app.comoBean.instance(data, {
  942. offset: (data.page - 1) * data.limit, limit: data.limit, where: {
  943. user_id: data.user_id,
  944. type: { [seq.Op.in]: [ 1, 2 ] },
  945. },
  946. order: [ [ 'type', 'asc' ] ],
  947. });
  948. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '新用户福利查询失败,请稍候重试', true, true);
  949. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  950. } catch (err) {
  951. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  952. }
  953. }
  954. /**
  955. * [newUserBenefits 获取每日红包]
  956. * @return {[type]} [description]
  957. */
  958. async dayLucky() {
  959. const that = this;
  960. try {
  961. const data = await that.ctx.validate(that.luckyValidate, await that.ctx.anyParse());
  962. // 2023/11/17 用户今天是否已经抽奖
  963. const user = await that.useModel.findOne({
  964. where: { user_id: data.user_id },
  965. });
  966. const isTodayLucky = await that.service.baseUtils.isToday(user.lucky_time);
  967. // const isTodayLucky = false;
  968. if (isTodayLucky) {
  969. throw new Error('您今天已经抽奖了哦,明天再来吧!');
  970. } else {
  971. // 2023/11/17 : 发起概率抽奖 发放奖项 (红包上限)
  972. let prizes;
  973. if (user.money > 999) {
  974. prizes = [
  975. { reward: 6, weight: 1 },
  976. { reward: 1, weight: 95 },
  977. { reward: 10, weight: 1 },
  978. { reward: 8, weight: 1 },
  979. { reward: 30, weight: 1 },
  980. { reward: 20, weight: 1 }
  981. ];
  982. } else {
  983. prizes = [
  984. { reward: 6, weight: 4 },
  985. { reward: 1, weight: 1 },
  986. { reward: 10, weight: 50 },
  987. { reward: 8, weight: 10 },
  988. { reward: 30, weight: 5 },
  989. { reward: 20, weight: 30 }
  990. ];
  991. }
  992. const prizeAward = await that.lottery(prizes);
  993. // 2023/11/21 发放红包奖励
  994. // console.log(prizeAward);
  995. await that.service.shop.userMoneyAdd(user.user_id, prizeAward.reward, null, '每日抽奖红包', 0, 4);
  996. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', prizeAward, false));
  997. }
  998. } catch (err) {
  999. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  1000. }
  1001. }
  1002. //权重抽奖函数
  1003. async lottery(prizes) {
  1004. let total = 0;
  1005. let percent;
  1006. //下标标记数组
  1007. let index = [];
  1008. for (let i = 0; i < prizes.length; i++) {
  1009. //判断元素的权重,为了实现小数权重,先将所有的值放大100倍
  1010. percent = 'undefined' != typeof (prizes[i].weight) ? prizes[i].weight : 0;
  1011. for (let j = 0; j < percent; j++) {
  1012. index.push(i);
  1013. }
  1014. total += percent;
  1015. }
  1016. //随机数值
  1017. let rand = Math.floor(Math.random() * total);
  1018. return prizes[index[rand]];
  1019. };
  1020. /**
  1021. * 更新用户信息
  1022. * @date:2023/10/20
  1023. */
  1024. async updateUserInfo() {
  1025. const that = this;
  1026. try {
  1027. const data = await that.ctx.validate(that.updateValidate, await that.ctx.anyParse());
  1028. // 2023/10/20 更新用户信息
  1029. const dataParam = {};
  1030. if (data.is_office) {
  1031. dataParam.is_office = true;
  1032. }
  1033. if (data.is_family) {
  1034. dataParam.is_family = true;
  1035. }
  1036. dataParam.update_ttime = that.app.szjcomo.date('Y-m-d H:i:s');
  1037. const updateBean = await that.app.comoBean.instance(dataParam, { where: { user_id: data.user_id } });
  1038. const result = await that.service.base.update(updateBean, that.useModel, '微信用户信息更新失败,请重试');
  1039. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  1040. } catch (e) {
  1041. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  1042. }
  1043. }
  1044. };