user.js 37 KB

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