user.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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' ],
  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' ],
  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. }, { where: { user_id: user.user_id } });
  343. await that.service.base.update(updateBean, that.useModel, '微信用户登录时间更新失败,请重试');
  344. }
  345. return user;
  346. }
  347. /**
  348. * [writeWxUser 写入微信用户]
  349. * @param {Object} userInfo [description]
  350. * @return {[type]} [description]
  351. */
  352. async writeWxUser(userInfo = {}) {
  353. const that = this;
  354. const data = await that.ctx.validate(that.wxuserValidate, userInfo);
  355. const createBean = await that.app.comoBean.instance(data);
  356. const result = await that.service.base.create(createBean, that.useModel, '添加微信用户失败,请重试');
  357. return {
  358. user_id: result.dataValues.user_id,
  359. account_name: result.dataValues.account_name,
  360. nickname: result.dataValues.nickname,
  361. headimgurl: result.dataValues.headimgurl,
  362. openid: result.dataValues.openid,
  363. unionid: result.dataValues.unionid,
  364. is_office: result.dataValues.is_office,
  365. is_family: result.dataValues.is_family,
  366. };
  367. }
  368. /**
  369. * [userMoney 获取用户余额]
  370. * @return {[type]} [description]
  371. */
  372. async userMoney() {
  373. const that = this;
  374. try {
  375. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  376. const result = await that.service.shop.getUserMoney(data.user_id);
  377. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  378. } catch (err) {
  379. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  380. }
  381. }
  382. /**
  383. * [userMoney 获取用户账户余额]
  384. * @return {[type]} [description]
  385. */
  386. async userAccount() {
  387. const that = this;
  388. try {
  389. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  390. const result = await that.service.shop.getUserAccount(data.user_id);
  391. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  392. } catch (err) {
  393. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  394. }
  395. }
  396. /**
  397. * [userMoneyLog 用户资金明细]
  398. * @return {[type]} [description]
  399. */
  400. async userMoneyLog() {
  401. const that = this;
  402. try {
  403. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  404. const selectBean = await that.app.comoBean.instance(data, {
  405. offset: (data.page - 1) * data.limit,
  406. limit: data.limit,
  407. where: { user_id: data.user_id },
  408. order: [[ 'log_id', 'desc' ]],
  409. attributes: [ 'log_id', 'log_desc', 'change_time', 'money', 'type', 'inviter_id', 'inviter_name', 'inviter_img' ],
  410. });
  411. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '查询资金明细失败,请稍候重试', true, true);
  412. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  413. } catch (err) {
  414. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  415. }
  416. }
  417. /**
  418. * [userMoneyLog 用户分佣明细]
  419. * @return {[type]} [description]
  420. */
  421. async userCommissionLog() {
  422. const that = this;
  423. try {
  424. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  425. const selectBean = await that.app.comoBean.instance(data, {
  426. // offset: (data.page - 1) * data.limit, limit: data.limit,
  427. where: { user_id: data.user_id },
  428. order: [[ 'log_id', 'desc' ]],
  429. attributes: [ 'log_desc', 'create_time', 'commission', 'type', 'inviter_id', 'inviter_name', 'inviter_img' ],
  430. });
  431. // 2022/11/28 直接查询所有数据 不分页
  432. const result = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询分佣明细失败,请稍候重试', false, true);
  433. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  434. } catch (err) {
  435. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  436. }
  437. }
  438. /**
  439. * [userMoneyLog 用户餐币明细]
  440. * @return {[type]} [description]
  441. */
  442. async coinDetail() {
  443. const that = this;
  444. try {
  445. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  446. const selectBean = await that.app.comoBean.instance(data, {
  447. where: { user_id: data.user_id },
  448. order: [[ 'log_id', 'desc' ]],
  449. });
  450. // 2022/11/28 直接查询所有数据 不分页
  451. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询分佣明细失败,请稍候重试', false, true);
  452. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  453. } catch (err) {
  454. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  455. }
  456. }
  457. // 2023/2/28 用户餐饮币账户列表
  458. async userDiningCoin() {
  459. const that = this;
  460. try {
  461. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  462. const selectBean = await that.app.comoBean.instance(data, {
  463. where: { user_id: data.user_id, expired: false },
  464. });
  465. // 2023/2/28 直接查询所有数据 不分页
  466. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户失败,请稍候重试', false, true);
  467. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  468. } catch (err) {
  469. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  470. }
  471. }
  472. /**
  473. * 用户指定商家餐币账户余额
  474. * @return {Promise<*>}
  475. */
  476. async userCouldTransferCoin() {
  477. const that = this;
  478. try {
  479. const data = await that.ctx.validate(that.userTransferValidate, await that.ctx.getParse());
  480. const res = await that.getCouldTransferCoin(data);
  481. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', { couldTransferCoins: res.account }, false));
  482. } catch (err) {
  483. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  484. }
  485. }
  486. /**
  487. * 用户可在指定商家消费的餐币账户余额
  488. * @param data
  489. */
  490. async getCouldTransferCoin(data) {
  491. const that = this;
  492. if (!data.diningCoinCode) {
  493. throw new Error('参数错误');
  494. }
  495. const userInfo = await that.app.model.Users.findOne({
  496. where: { openid: data.diningCoinCode },
  497. attributes: [ 'user_id' ],
  498. });
  499. if (!userInfo || userInfo.user_id < 0) {
  500. throw new Error('参数错误');
  501. }
  502. const businessInfo = await that.app.model.Users.findOne({
  503. where: { user_id: data.user_id },
  504. attributes: [ 'partner_id' ],
  505. });
  506. if (!businessInfo || businessInfo.partner_id < 1) {
  507. throw new Error('抱歉,您不是源森家具的合作商户,无权收款。');
  508. }
  509. const seq = that.app.Sequelize;
  510. const selectBean = await that.app.comoBean.instance({}, {
  511. where: {
  512. user_id: userInfo.user_id,
  513. // partner_id: businessInfo.partner_id,
  514. // 2023/4/11 补充通用餐币
  515. partner_id: { [seq.Op.in]: [ businessInfo.partner_id, 1 ] },
  516. expired: false,
  517. },
  518. attributes: [[ seq.fn('sum', seq.col('account')), 'account' ]],
  519. });
  520. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户余额失败,请稍候重试', false, false);
  521. const res = JSON.parse(JSON.stringify(result));
  522. res.customer_id = userInfo.user_id;
  523. res.partner_id = businessInfo.partner_id;
  524. res.business_id = data.user_id;
  525. return res;
  526. }
  527. /**
  528. * 商家可提现餐币金额
  529. * @return {Promise<*>}
  530. */
  531. async businessDiningCoinCouldCash() {
  532. const that = this;
  533. try {
  534. const data = await that.ctx.validate(that.businessCashCoinValidate, await that.ctx.getParse());
  535. const res = await that.getDiningCoinCouldCash(data);
  536. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', res, false));
  537. } catch (err) {
  538. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  539. }
  540. }
  541. /**
  542. * 商家可提现餐币金额
  543. * @param data
  544. */
  545. async getDiningCoinCouldCash(data) {
  546. const that = this;
  547. const businessInfo = await that.app.model.Users.findOne({
  548. where: { user_id: data.user_id },
  549. });
  550. if (!businessInfo || businessInfo.partner_id < 0) {
  551. throw new Error('您的账号还没有绑定的合作商铺哦');
  552. }
  553. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  554. where: { id: businessInfo.partner_id },
  555. });
  556. if (!partnerInfo || partnerInfo.user_id !== data.user_id) {
  557. throw new Error('您的账号没有权限提现餐费哦');
  558. }
  559. const seq = that.app.Sequelize;
  560. const currentDateTime = that.app.szjcomo.date('Y-m-d H:i:s');
  561. const sevenDayTime = 24 * 60 * 60 * 1000; // 2023/3/1 24小时后可提现
  562. const endTimeStamp = Date.parse(currentDateTime) - sevenDayTime;
  563. const endDateTime = that.app.szjcomo.date('Y-m-d H:i:s', endTimeStamp / 1000);
  564. // 2023/3/1 查询24小时前的所得餐币总和 以及所有时间提现的总和 再求和 即为 可提现餐币金额
  565. // todo : 特殊情况 商家管理员有自家绑定的商铺 餐币消费支出
  566. const selectBean = await that.app.comoBean.instance({}, {
  567. where: {
  568. user_id: businessInfo.user_id,
  569. partner_id: businessInfo.partner_id,
  570. create_time: { [seq.Op.lte]: endDateTime },
  571. account: { [seq.Op.gte]: 0 },
  572. },
  573. attributes: [[ seq.fn('sum', seq.col('account')), 'account' ]],
  574. });
  575. const coinResult = await that.service.base.select(selectBean, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  576. const selectBean2 = await that.app.comoBean.instance({}, {
  577. where: {
  578. user_id: businessInfo.user_id,
  579. partner_id: businessInfo.partner_id,
  580. account: { [seq.Op.lte]: 0 },
  581. type: { [seq.Op.ne]: -1 },
  582. },
  583. attributes: [[ seq.fn('sum', seq.col('account')), 'account' ]],
  584. });
  585. const cashResult = await that.service.base.select(selectBean2, that.app.model.DinnerCoinLogs, '查询商家可提现餐币金额失败,请稍候重试', false, false);
  586. const coinRes = JSON.parse(JSON.stringify(coinResult));
  587. const cashRes = JSON.parse(JSON.stringify(cashResult));
  588. const couldCash = new Decimal(coinRes.account ? coinRes.account : 0)
  589. .add(new Decimal(cashRes.account ? cashRes.account : 0))
  590. .toNumber();
  591. coinRes.all_coin_could_cash = couldCash > 0 ? couldCash : 0;
  592. coinRes.all_cash = cashRes.account;
  593. coinRes.partner_id = businessInfo.partner_id;
  594. coinRes.partner_fees = partnerInfo.partner_fees;
  595. return coinRes;
  596. }
  597. /**
  598. * 商家申请核销餐币
  599. * @return {Promise<void>}
  600. */
  601. async coinTransfer() {
  602. const that = this;
  603. const seq = that.app.Sequelize;
  604. const transaction = await that.app.model.transaction();
  605. try {
  606. const data = await that.ctx.validate(that.coinTransferValidate, await that.ctx.postParse());
  607. // 2023/2/28 获取可核销餐币
  608. const intervalTime = Date.parse(that.app.szjcomo.date('Y-m-d H:i:s')) - data.time;
  609. if (intervalTime > 10 * 60 * 1000) {
  610. throw new Error('顾客付款码已超时失效,请重新扫码!');
  611. }
  612. const transferParams = await that.getCouldTransferCoin(data);
  613. if (data.coinAmount > 0 && data.coinAmount <= transferParams.account) {
  614. // 2023/2/28 发起核销收取餐币
  615. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  616. where: { id: transferParams.partner_id },
  617. });
  618. // 2023/4/12 核销餐币 包含通用电子餐币
  619. const selectBean = await that.app.comoBean.instance({}, {
  620. where: {
  621. user_id: transferParams.customer_id,
  622. // partner_id: transferParams.partner_id,
  623. partner_id: { [seq.Op.in]: [ transferParams.partner_id, 1 ] },
  624. expired: false,
  625. },
  626. order: [[ 'partner_id', 'desc' ], [ 'ori_partner', 'desc' ]],
  627. });
  628. // 2023/2/28 查询所有指定商家餐币
  629. const result = await that.service.base.select(selectBean, that.app.model.DinnerCoins, '查询餐饮币账户失败,请稍候重试', false, true);
  630. const customerAccounts = [];
  631. let needAccount = 0;
  632. for (const resultElement of result) {
  633. needAccount += resultElement.account;
  634. customerAccounts.push(JSON.parse(JSON.stringify(resultElement)));
  635. if (needAccount >= data.coinAmount) {
  636. break;
  637. }
  638. }
  639. let firstCoinAmount;
  640. let secondCoinAmount;
  641. let thirdCoinAmount;
  642. let fourthCoinAmount;
  643. let incomeCoinAmount = 0;
  644. switch (customerAccounts.length) {
  645. case 1:
  646. firstCoinAmount = data.coinAmount;
  647. secondCoinAmount = 0;
  648. thirdCoinAmount = 0;
  649. fourthCoinAmount = 0;
  650. break;
  651. case 2:
  652. firstCoinAmount = customerAccounts[0].account;
  653. secondCoinAmount = data.coinAmount - firstCoinAmount;
  654. thirdCoinAmount = 0;
  655. fourthCoinAmount = 0;
  656. break;
  657. case 3:
  658. firstCoinAmount = customerAccounts[0].account;
  659. secondCoinAmount = customerAccounts[1].account;
  660. thirdCoinAmount = data.coinAmount - firstCoinAmount - secondCoinAmount;
  661. fourthCoinAmount = 0;
  662. break;
  663. case 4:
  664. firstCoinAmount = customerAccounts[0].account;
  665. secondCoinAmount = customerAccounts[1].account;
  666. thirdCoinAmount = customerAccounts[2].account;
  667. fourthCoinAmount = data.coinAmount - firstCoinAmount - secondCoinAmount - thirdCoinAmount;
  668. break;
  669. default:
  670. break;
  671. }
  672. // =========================================== 2023/3/1 第一个账户划账======================================
  673. await that.doTransferCoins(that, transferParams, firstCoinAmount, partnerInfo, transaction, customerAccounts, 0);
  674. incomeCoinAmount += firstCoinAmount * (customerAccounts[0].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  675. // =============================== 2023/3/1 需要第二个账户来继续划账 ==========================================
  676. if (customerAccounts.length > 1 && secondCoinAmount > 0) {
  677. await that.doTransferCoins(that, transferParams, secondCoinAmount, partnerInfo, transaction, customerAccounts, 1);
  678. incomeCoinAmount += secondCoinAmount * (customerAccounts[1].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  679. }
  680. // =============================== 2023/3/18 需要第三个账户来继续划账 ==========================================
  681. if (customerAccounts.length > 2 && thirdCoinAmount > 0) {
  682. await that.doTransferCoins(that, transferParams, thirdCoinAmount, partnerInfo, transaction, customerAccounts, 2);
  683. incomeCoinAmount += thirdCoinAmount * (customerAccounts[2].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  684. }
  685. // =============================== 2023/3/18 需要第四个账户来继续划账 ==========================================
  686. if (customerAccounts.length > 3 && fourthCoinAmount > 0) {
  687. await that.doTransferCoins(that, transferParams, fourthCoinAmount, partnerInfo, transaction, customerAccounts, 3);
  688. incomeCoinAmount += fourthCoinAmount * (customerAccounts[3].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  689. }
  690. await transaction.commit();
  691. incomeCoinAmount = incomeCoinAmount.toFixed(2);
  692. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', {
  693. incomeCoinAmount,
  694. transferCoinAmount: data.coinAmount,
  695. }, false));
  696. }
  697. throw new Error('输入的核销金额有误,请稍后重试');
  698. } catch (e) {
  699. if (transaction) transaction.rollback();
  700. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  701. }
  702. }
  703. // 2023/3/1 餐币划账 具体逻辑和操作
  704. async doTransferCoins(that, transferParams, coinAmount, partnerInfo, transaction, customerAccounts, index) {
  705. // 2023/3/6 获取顾客信息
  706. const customerInfo = await that.app.model.Users.findOne({
  707. where: { user_id: transferParams.customer_id },
  708. transaction,
  709. raw: true,
  710. });
  711. // 2023/3/1 扣去顾客餐币
  712. await that.service.diningCoin.addDiningCoinChangeLog({
  713. user_id: transferParams.customer_id,
  714. order_id: -1,
  715. partner_id: customerAccounts[index].partner_id,
  716. type: 3,
  717. account: -coinAmount,
  718. log_desc: partnerInfo.name + ' 消费',
  719. }, transaction);
  720. // 2023/3/1 更新顾客账户
  721. const customerAccountBean = await that.app.comoBean.instance({
  722. account: customerAccounts[index].account - coinAmount,
  723. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  724. }, {
  725. where: {
  726. user_id: transferParams.customer_id,
  727. ori_partner: customerAccounts[index].ori_partner,
  728. partner_id: customerAccounts[index].partner_id,
  729. expired: false,
  730. }, transaction,
  731. });
  732. if (customerAccounts[index].account === coinAmount) {
  733. // 2023/3/1 删除0元账户
  734. await that.service.base.delete(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币清零更新失败,请重试');
  735. } else {
  736. await that.service.base.update(customerAccountBean, that.app.model.DinnerCoins, '顾客餐饮币余额更新失败,请重试');
  737. }
  738. // 2023/3/1 划入商家账户记录
  739. const businessCoinAmount = coinAmount * (customerAccounts[index].ori_partner ? partnerInfo.rate_from_partner : partnerInfo.rate_default);
  740. await that.service.diningCoin.addDiningCoinChangeLog({
  741. user_id: transferParams.business_id,
  742. order_id: -1,
  743. partner_id: transferParams.partner_id,
  744. type: 4,
  745. account: businessCoinAmount,
  746. log_desc: '核销收取餐币',
  747. ori_partner: customerAccounts[index].ori_partner,
  748. customer_id: customerInfo.user_id,
  749. customer_name: customerInfo.nickname,
  750. customer_img: customerInfo.headimgurl,
  751. }, transaction);
  752. // 2023/2/28 查询商家餐饮币账户列表 添加 或 更新账户余额
  753. const info = await that.app.model.DinnerCoins.findOne({
  754. where: {
  755. user_id: transferParams.business_id,
  756. // ori_partner: customerAccounts[index].ori_partner,
  757. partner_id: transferParams.partner_id,
  758. expired: false,
  759. },
  760. transaction,
  761. raw: true,
  762. });
  763. if (!info) {
  764. // 2023/2/27 没有对应类型的餐饮币 则插入该类型的餐饮币账户
  765. const createData = {
  766. user_id: transferParams.business_id,
  767. account: businessCoinAmount,
  768. // ori_partner: customerAccounts[index].ori_partner,
  769. ori_partner: true,
  770. partner_id: transferParams.partner_id,
  771. create_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  772. expired: false,
  773. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  774. };
  775. createData.partner_name = partnerInfo.name;
  776. createData.partner_address = partnerInfo.address;
  777. createData.partner_tel = partnerInfo.tel_num;
  778. createData.partner_opening_time = partnerInfo.opening_time;
  779. const createBean = await that.app.comoBean.instance(createData, { transaction });
  780. await that.service.base.create(createBean, that.app.model.DinnerCoins, '餐饮币发放失败,请重试');
  781. } else {
  782. const updateBean = await that.app.comoBean.instance({
  783. account: info.account + businessCoinAmount,
  784. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  785. expired: false,
  786. expired_time: that.app.szjcomo.date('Y-m-d H:i:s', parseInt(+new Date() + '') / 1000 + 90 * 24 * 60 * 60),
  787. }, {
  788. where: {
  789. user_id: transferParams.business_id,
  790. // ori_partner: customerAccounts[index].ori_partner,
  791. partner_id: transferParams.partner_id,
  792. }, transaction,
  793. });
  794. await that.service.base.update(updateBean, that.app.model.DinnerCoins, '餐饮币余额更新失败,请重试');
  795. }
  796. }
  797. /**
  798. * 用户可提现金额(求和)
  799. * @return {Promise<*>}
  800. */
  801. async userCommissionCouldCash() {
  802. const that = this;
  803. try {
  804. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  805. const result = await that.getCouldCashCommission(data.user_id);
  806. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  807. } catch (err) {
  808. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  809. }
  810. }
  811. /**
  812. * 获取用户可提现金额(求和)
  813. * @return {Promise<void>}
  814. */
  815. async getCouldCashCommission(user_id = -1) {
  816. if (user_id <= 0) {
  817. throw new Error('参数错误');
  818. }
  819. const that = this;
  820. const seq = that.app.Sequelize;
  821. const currentDateTime = that.app.szjcomo.date('Y-m-d H:i:s');
  822. const sevenDayTime = 7 * 24 * 60 * 60 * 1000;
  823. const endTimeStamp = Date.parse(currentDateTime) - sevenDayTime;
  824. const endDateTime = that.app.szjcomo.date('Y-m-d H:i:s', endTimeStamp / 1000);
  825. // 2022/11/28 查询7天前的所得分佣总和 以及所有时间得提现总和 再求和 即为 可提现金额
  826. const selectBean = await that.app.comoBean.instance({ user_id }, {
  827. where: { user_id, create_time: { [seq.Op.lte]: endDateTime }, commission: { [seq.Op.gte]: 0 } },
  828. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_commission' ]],
  829. });
  830. const commissionResult = await that.service.base.select(selectBean, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  831. const selectBean2 = await that.app.comoBean.instance({ user_id }, {
  832. where: { user_id, commission: { [seq.Op.lte]: 0 }, type: { [seq.Op.ne]: -1 } }, // type-1提现失败类型
  833. attributes: [ 'user_id', [ seq.fn('sum', seq.col('commission')), 'all_cash' ]],
  834. });
  835. const cashResult = await that.service.base.select(selectBean2, that.app.model.UsersCommissionLogs, '查询佣金失败,请稍候重试', false, false);
  836. const commRes = JSON.parse(JSON.stringify(commissionResult));
  837. const cashRes = JSON.parse(JSON.stringify(cashResult));
  838. commRes.all_commission_could_cash = new Decimal(commRes.all_commission ? commRes.all_commission : 0)
  839. .add(new Decimal(cashRes.all_cash ? cashRes.all_cash : 0))
  840. .toNumber();
  841. commRes.all_cash = cashRes.all_cash;
  842. return commRes;
  843. }
  844. /**
  845. * 用户佣金提现
  846. * @return {Promise<void>}
  847. */
  848. async userCashOut() {
  849. const that = this;
  850. try {
  851. const data = await that.ctx.validate(that.cashOutValidate, await that.ctx.postParse());
  852. // 2023/1/17 获取可提现佣金额度
  853. const res = await that.getCouldCashCommission(data.user_id);
  854. if (data.cash_amount >= 0.1 && data.cash_amount <= res.all_commission_could_cash) {
  855. // 2023/1/31 发起提现
  856. // todo : 用户分佣提现 1.扣取税费;2.用户分佣转通用电子餐费;
  857. const result = await that.service.wxPay.transfer(data);
  858. // 2023/1/31 提现状态
  859. if (result.status != 200) {
  860. throw new Error('提现转账出现异常,请联系客服后再重试');
  861. }
  862. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  863. }
  864. throw new Error('输入提现金额有误,请稍后重试');
  865. } catch (e) {
  866. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  867. }
  868. }
  869. /**
  870. * 用户佣金转电子餐费
  871. * @return {Promise<void>}
  872. */
  873. async commission2DiningCoin() {
  874. // 2023/11/17 todo: 佣金转电子餐费
  875. }
  876. /**
  877. * 商家餐币提现
  878. * @return {Promise<*>}
  879. */
  880. async userCoinCashOut() {
  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.getDiningCoinCouldCash(data);
  886. data.partner_id = res.partner_id;
  887. if (data.cash_amount >= 0.1 && data.cash_amount <= (res.all_coin_could_cash - res.partner_fees)) {
  888. // 2023/1/31 发起提现
  889. const result = await that.service.businessPayService.transfer(data);
  890. // 2023/1/31 提现状态
  891. if (result.status != 200) {
  892. throw new Error('提现转账出现异常,请联系客服后再重试');
  893. }
  894. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  895. }
  896. throw new Error('输入提现金额有误,请稍后重试');
  897. } catch (e) {
  898. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  899. }
  900. }
  901. /**
  902. * [newUserBenefits 查询新用户福利]
  903. * @return {[type]} [description]
  904. */
  905. async newUserBenefits() {
  906. const that = this;
  907. try {
  908. const data = await that.ctx.validate(that.userMoneyValidate, await that.ctx.getParse());
  909. const seq = that.app.Sequelize;
  910. const selectBean = await that.app.comoBean.instance(data, {
  911. offset: (data.page - 1) * data.limit, limit: data.limit, where: {
  912. user_id: data.user_id,
  913. type: { [seq.Op.in]: [ 1, 2 ] },
  914. },
  915. order: [[ 'type', 'asc' ]],
  916. });
  917. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '新用户福利查询失败,请稍候重试', true, true);
  918. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  919. } catch (err) {
  920. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  921. }
  922. }
  923. /**
  924. * [newUserBenefits 获取每日红包]
  925. * @return {[type]} [description]
  926. */
  927. async dayLucky() {
  928. const that = this;
  929. try {
  930. const data = await that.ctx.validate(that.luckyValidate, await that.ctx.anyParse());
  931. // 2023/11/17 todo: 用户今天抽奖校验
  932. const user = await that.useModel.findOne({
  933. where: { user_id: data.user_id },
  934. });
  935. // 2023/11/17 todo: 发起概率抽奖 发放奖项 (红包上限)
  936. const seq = that.app.Sequelize;
  937. const selectBean = await that.app.comoBean.instance(data, {
  938. offset: (data.page - 1) * data.limit, limit: data.limit, where: {
  939. user_id: data.user_id,
  940. type: { [seq.Op.in]: [ 1, 2 ] },
  941. },
  942. order: [[ 'type', 'asc' ]],
  943. });
  944. const result = await that.service.base.select(selectBean, that.app.model.UsersMoneyLogs, '新用户福利查询失败,请稍候重试', true, true);
  945. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  946. } catch (err) {
  947. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  948. }
  949. }
  950. /**
  951. * 更新用户信息
  952. * @date:2023/10/20
  953. */
  954. async updateUserInfo() {
  955. const that = this;
  956. try {
  957. const data = await that.ctx.validate(that.updateValidate, await that.ctx.anyParse());
  958. // 2023/10/20 更新用户信息
  959. const dataParam = {};
  960. if (data.is_office) {
  961. dataParam.is_office = true;
  962. }
  963. if (data.is_family) {
  964. dataParam.is_family = true;
  965. }
  966. dataParam.update_ttime = that.app.szjcomo.date('Y-m-d H:i:s');
  967. const updateBean = await that.app.comoBean.instance(dataParam, { where: { user_id: data.user_id } });
  968. const result = await that.service.base.update(updateBean, that.useModel, '微信用户信息更新失败,请重试');
  969. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  970. } catch (e) {
  971. return that.ctx.appJson(that.app.szjcomo.appResult(e.message));
  972. }
  973. }
  974. };