BonusSend.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/3/18
  6. * Time: 上午11:06
  7. */
  8. namespace common\helpers\bonus;
  9. use common\components\ActiveRecord;
  10. use common\helpers\DataBak;
  11. use common\helpers\Form;
  12. use common\helpers\Tool;
  13. use common\helpers\user\Balance;
  14. use common\helpers\user\Info;
  15. use common\helpers\user\Reconsume;
  16. use common\helpers\user\Status;
  17. use common\libs\api\sms\SmsApi;
  18. use common\libs\swoole\Process;
  19. use common\models\DealType;
  20. use common\models\PerfPeriod;
  21. use common\models\DecOrder;
  22. use common\models\EmployLevel;
  23. use common\models\UserBonus;
  24. use common\models\UserPerfMonthUpdate;
  25. use common\models\UserPeriodPoints;
  26. use common\models\UserWallet;
  27. use common\models\UserInfo;
  28. use common\models\UserPerf;
  29. use common\models\UserPerfUpdate;
  30. use common\models\UserTeamwork;
  31. use common\models\YearHighestEmpLv;
  32. use yii\base\BaseObject;
  33. use yii\base\StaticInstanceTrait;
  34. use common\helpers\Cache;
  35. use common\helpers\Date;
  36. use common\models\CalcBonus;
  37. use common\models\PerfMonth;
  38. use common\models\User;
  39. use Yii;
  40. use common\models\Period;
  41. use yii\base\Exception;
  42. use yii\db\Expression;
  43. class BonusSend extends BaseObject {
  44. use StaticInstanceTrait;
  45. private $_limit = 1000;
  46. private $_appUserId = null;
  47. private $_sysConfig = [];
  48. private $_decLevelConfig = [];
  49. private $_empLevelConfig = [];
  50. private $_decRoleConfig = [];
  51. private $_errors = [];
  52. private $_periodNum = 0;
  53. private $_periodId;
  54. private $_isCalcMonth = 0;
  55. private $_isCalcYear = 0;
  56. private $_calcYear;
  57. private $_calcMonth;
  58. private $_calcYearMonth;
  59. private $_lastCalcYear;
  60. private $_lastCalcMonth;
  61. private $_lastCalcYearMonth;
  62. private $_workerId;
  63. private $_workerNum;
  64. public function init(int $periodNum = 0, $appUserId = null, $workerId = null, $workerNum = null) {
  65. parent::init();
  66. $this->_sysConfig = Cache::getSystemConfig();
  67. $this->_decLevelConfig = Cache::getDecLevelConfig();
  68. $this->_empLevelConfig = Cache::getEmpLevelConfig();
  69. $this->_decRoleConfig = CalcCache::getDecRoleConfig($this->_periodNum);
  70. $this->_periodNum = $periodNum;
  71. $this->_appUserId = $appUserId;
  72. $this->_workerId = $workerId;
  73. $this->_workerNum = $workerNum;
  74. }
  75. /**
  76. * 设置期数
  77. * @param int $periodNum
  78. * @return int
  79. */
  80. public function setPeriodNum(int $periodNum) {
  81. return $this->_periodNum = $periodNum;
  82. }
  83. /**
  84. * 获取期数
  85. * @return int
  86. */
  87. public function getPeriodNum() {
  88. return $this->_periodNum;
  89. }
  90. /**
  91. * 加入错误错误
  92. * @param $attr
  93. * @param $error
  94. */
  95. public function addError($attr, $error) {
  96. $this->_errors[$attr][] = $error;
  97. }
  98. /**
  99. * 获取错误信息
  100. * @return array
  101. */
  102. public function getErrors() {
  103. return $this->_errors;
  104. }
  105. /**
  106. * 进行奖金发放步骤
  107. * @return bool
  108. */
  109. public function sendStep() {
  110. try {
  111. $t1 = microtime(true);
  112. // 初始化
  113. $this->initTask();
  114. $t2 = microtime(true);
  115. echo('初始化完成,当前期数【' . $this->_periodNum . '】,耗时:' . round($t2 - $t1, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  116. // 改变状态
  117. $this->setSendStatus('start');
  118. $t3 = microtime(true);
  119. echo('改变状态完成,耗时:' . round($t3 - $t2, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  120. $this->_updatePercent(20);
  121. //Yii::$app->db->close();
  122. //Yii::$app->dbShop->close();
  123. // 更新聘级
  124. $this->updateEmpLevel();
  125. $this->_updatePercent(40);
  126. $t4 = microtime(true);
  127. echo('更新聘级完成,耗时:' . round($t4 - $t3, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  128. // 发放奖金
  129. $this->sendBonusLoop();
  130. $this->_updatePercent(60);
  131. $t5 = microtime(true);
  132. echo('发放奖金完成,耗时:' . round($t5 - $t4, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  133. // 更新会员上次报单级别
  134. // $this->updateUserDevLv();
  135. // $this->_updatePercent(80);
  136. $t6 = microtime(true);
  137. // echo('更新会员上次报单级别完成,耗时:' . round($t6 - $t5, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  138. // 更新会员累计业绩
  139. $this->updateUserPerf();
  140. $this->_updatePercent(80);
  141. $t7 = microtime(true);
  142. echo('更新会员累计业绩完成,耗时:' . round($t7 - $t6, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  143. $this->updateUserPerfMonth();
  144. $this->_updatePercent(90);
  145. $t8 = microtime(true);
  146. echo('更新会员累计月业绩完成,耗时:' . round($t8 - $t7, 3) . ',内存使用:' . (round(memory_get_usage() / 1024 / 1024, 3)) . 'MB' . PHP_EOL);
  147. // 开启子进程去完成下面的循环发放和循环改聘级和循环更新累计业绩
  148. /*$process = new Process('sendBonus', 3);
  149. $process->run(function($workId, $pmid){
  150. $this->processStep($workId);
  151. });
  152. while (true){
  153. if($process->isFinish()) break;
  154. }
  155. unset($process);
  156. $this->_updatePercent(90);
  157. $t4 = microtime(true);
  158. echo('所有子进程的任务完成,耗时:'.round($t4 - $t3, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);*/
  159. echo('全部奖金发放完成,耗时:'.round($t7 - $t1, 3).',内存使用:'.(round(memory_get_usage()/1024/1024, 3)).'MB'.PHP_EOL);
  160. $this->_updatePercent(100);
  161. } catch (\Exception $e) {
  162. $this->addError('sendBonus', $e->getMessage());
  163. return false;
  164. }
  165. if (count($this->_errors) > 0) {
  166. return false;
  167. }
  168. return true;
  169. }
  170. /**
  171. * 需要多进程执行的任务
  172. * @param $workId
  173. * @throws \yii\db\Exception
  174. */
  175. public function processStep($workId = null) {
  176. if ($workId == 1 || $workId === null) {
  177. // 发放奖金
  178. $this->sendBonusLoop();
  179. }
  180. if ($workId == 2 || $workId === null) {
  181. // 更新聘级
  182. $this->updateEmpLevel();
  183. }
  184. if ($workId == 3 || $workId === null) {
  185. // 更新会员累计业绩
  186. $this->updateUserPerf();
  187. }
  188. Yii::$app->db->close();
  189. Yii::$app->dbShop->close();
  190. }
  191. /**
  192. * 初始化发放任务
  193. * @throws Exception
  194. */
  195. public function initTask() {
  196. $this->_errors = [];
  197. $periodNum = $this->_periodNum;
  198. // 获取传入期数的相关信息
  199. $periodObj = Period::instance();
  200. $periodDataArr = $periodObj->setPeriodNum($periodNum);
  201. $this->_periodId = $periodDataArr['ID'];
  202. $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
  203. $this->_calcYear = $periodObj->getYear($periodNum);
  204. $this->_calcMonth = $periodObj->getMonth($periodNum);
  205. $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
  206. $lastYearMonthArr = $periodObj->getLastMonth($periodNum);
  207. $this->_lastCalcYear = $lastYearMonthArr['year'];
  208. $this->_lastCalcMonth = $lastYearMonthArr['month'];
  209. $this->_lastCalcYearMonth = $lastYearMonthArr['yearMonth'];
  210. }
  211. /**
  212. * 设置结算状态
  213. * @param $type
  214. * start|end|fail
  215. */
  216. public function setSendStatus($type) {
  217. Yii::$app->db->close();
  218. if ($type == 'start') {
  219. Period::updateAll(['IS_SENDING' => 1, 'SEND_STARTED_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  220. } elseif ($type == 'end') {
  221. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FINISH, 'SENT_AT' => Date::nowTime()], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  222. } elseif ($type == 'fail') {
  223. Period::updateAll(['IS_SENDING' => 0, 'IS_SENT' => Period::SEND_FAIL, 'SENT_AT' => 0], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  224. }
  225. }
  226. /**
  227. * 结束计算任务
  228. * @throws \yii\db\Exception
  229. */
  230. public function endTask() {
  231. CalcCache::clearAll($this->_periodNum);
  232. $this->setSendStatus('end');
  233. //@todo 先不备份数据
  234. // DataBak::backup($this->_periodNum);
  235. //发送复销短信
  236. // if ($this->_isCalcMonth && $this->_sysConfig['smsOpen']['VALUE']) {
  237. // $this->sendSmsLoop();
  238. // }
  239. }
  240. /**
  241. * 出现错误
  242. */
  243. public function errorTask() {
  244. $this->setSendStatus('fail');
  245. }
  246. /**
  247. * 发放奖金
  248. * @param int $page
  249. * @return bool
  250. * @throws \yii\db\Exception
  251. */
  252. public function sendBonusLoop($page=1) {
  253. echo sprintf("时间:[%s]数据库发奖,当前page为:【%s】" . PHP_EOL, date('Y-m-d H:i:s', time()), $page);
  254. $periodNum = $this->_periodNum;
  255. // 从奖金结算表中获取当期未发放的所有数据
  256. $allData = CalcBonus::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('(IS_SENT=0 OR IS_SENT=2) AND CALC_MONTH=:CALC_MONTH AND PERIOD_NUM=:PERIOD_NUM', [':CALC_MONTH' => $this->_calcYearMonth, ':PERIOD_NUM' => $periodNum])->limit($this->_limit)->asArray()->all();
  257. if ($allData) {
  258. $transaction = Yii::$app->db->beginTransaction();
  259. try {
  260. foreach ($allData as $key => $data) {
  261. // 期奖金
  262. // $periodAmount = $data['BONUS_QY'] + $data['BONUS_YC'] + $data['BONUS_XF'] + $data['BONUS_BD'] + $data['BONUS_TG'] + $data['BONUS_YJ'] + $data['BONUS_GX'] + $data['BONUS_GL'];
  263. $periodAmount = $data['BONUS_REAL'];
  264. // 获取本期结算的管理员
  265. // $period = Period::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
  266. // $updateAminId = $period['CALC_ADMIN_ID'];
  267. if ($periodAmount > 0) {
  268. Balance::changeUserBonus($data['USER_ID'], 'bonus', $periodAmount, [
  269. 'CALC_ID' => $data['ID'],
  270. 'REMARK' => 'From ' . $periodNum . '期',
  271. 'PERIOD_NUM' => $periodNum,
  272. 'QY' => $data['BONUS_QY'],
  273. 'FW' => $data['BONUS_FW'],
  274. 'YC' => $data['BONUS_YC'],
  275. 'VIP' => $data['BONUS_VIP'],
  276. 'BD' => $data['BONUS_BD'],
  277. 'TG' => $data['BONUS_TG'],
  278. 'YJ' => $data['BONUS_YJ'],
  279. 'GX' => $data['BONUS_GX'],
  280. 'GL' => $data['BONUS_GL'],
  281. 'ORI_QY' => $data['ORI_BONUS_QY'],
  282. 'ORI_YC' => $data['ORI_BONUS_YC'],
  283. 'ORI_VIP' => $data['ORI_BONUS_VIP'],
  284. 'ORI_STANDARD' => $data['ORI_BONUS_STANDARD'],
  285. 'ORI_BD' => $data['ORI_BONUS_BD'],
  286. 'ORI_TG' => $data['ORI_BONUS_TG'],
  287. 'ORI_YJ' => $data['ORI_BONUS_YJ'],
  288. 'ORI_GX' => $data['ORI_BONUS_GX'],
  289. 'ORI_GL' => $data['ORI_BONUS_GL'],
  290. 'RECONSUME_POINTS_TOTAL' => $data['RECONSUME_POINTS'],
  291. 'MANAGE_TAX' => $data['MANAGE_TAX'],
  292. 'BONUS_TOTAL' => $data['BONUS_TOTAL'],
  293. 'DEAL_TYPE_ID' => DealType::BONUS_SEND,
  294. 'SORT' => $key * 10,
  295. ]);
  296. // $this->_teamworkBonus($data['USER_ID'], $periodAmount, $key);
  297. }
  298. //发放重消积分
  299. if ($data['RECONSUME_POINTS'] > 0) {
  300. Balance::changeUserBonus($data['USER_ID'], 'reconsume_points', $data['RECONSUME_POINTS'], [
  301. 'CALC_ID' => $data['ID'],
  302. 'REMARK' => 'From ' . $periodNum . '期',
  303. 'PERIOD_NUM' => $periodNum,
  304. 'RECONSUME_POINTS' => $data['RECONSUME_POINTS'],
  305. 'DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_SEND,
  306. ]);
  307. }
  308. // 把记录标记为已发放状态
  309. CalcBonus::updateAll(['IS_SENT' => 1, 'SENT_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $data['ID']]);
  310. unset($periodAmount, $key, $data);
  311. }
  312. $transaction->commit();
  313. } catch (Exception $e) {
  314. $transaction->rollBack();
  315. $this->addError('sendBonus', '奖金发放失败,原因:' . $e->getMessage());
  316. return false;
  317. }
  318. unset($allData, $transaction);
  319. $page++;
  320. return $this->sendBonusLoop($page);
  321. }
  322. unset($allData);
  323. return true;
  324. }
  325. /**
  326. * 更新会员聘级
  327. * @param int $offset
  328. * @return bool
  329. * @throws \yii\db\Exception
  330. */
  331. public function updateEmpLevel(int $offset = 0) {
  332. if ($this->_isCalcMonth) {
  333. $allData = PerfMonth::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->offset($offset)->limit($this->_limit)->all();
  334. //@todo 用户级别不变则不更新
  335. $defaultEmpLv = EmployLevel::getDefaultLevelId();
  336. if ($allData) {
  337. $transaction = Yii::$app->db->beginTransaction();
  338. try {
  339. foreach ($allData as $data) {
  340. //@todo 用户级别不变则不更新
  341. if( $data['LAST_EMP_LV'] === $defaultEmpLv ) continue;
  342. User::updateAll(['EMP_LV' => $data['LAST_EMP_LV']], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  343. User::deleteBaseInfoFromRedis($data['USER_ID']);
  344. unset($data);
  345. }
  346. $transaction->commit();
  347. } catch (Exception $e) {
  348. $transaction->rollBack();
  349. $this->addError('updateEmpLevel', '更新聘级失败,原因:' . $e->getMessage());
  350. return false;
  351. }
  352. unset($transaction, $allData, $defaultEmpLv);
  353. return $this->updateEmpLevel($offset + $this->_limit);
  354. }
  355. unset($allData);
  356. }
  357. return true;
  358. }
  359. /**
  360. * 更新会员的累计业绩
  361. * @param int $offset
  362. * @return bool
  363. * @throws \yii\db\Exception
  364. */
  365. public function updateUserPerf(int $offset = 0) {
  366. $allData = PerfPeriod::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  367. if ($allData) {
  368. $transaction = Yii::$app->db->beginTransaction();
  369. try {
  370. foreach ($allData as $data) {
  371. $isUpdate = false;
  372. if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  373. // 判断本期是否已经更新过业绩
  374. if (!UserPerfUpdate::findUseDbCalc()->yearMonth($this->_calcYearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $data['USER_ID'], ':PERIOD_NUM' => $this->_periodNum])->exists()) {
  375. $isUpdate = true;
  376. // 更新业绩
  377. UserPerf::updateAll([
  378. 'PV_PCS_ZC' => new Expression('PV_PCS_ZC+' . $data['PV_PCS_ZC']),
  379. 'PV_PCS_YH' => new Expression('PV_PCS_YH+' . $data['PV_PCS_YH']),
  380. 'PV_PCS_ZG' => new Expression('PV_PCS_ZG+' . $data['PV_PCS_ZG']),
  381. 'PV_PCS_LS' => new Expression('PV_PCS_LS+' . $data['PV_PCS_LS']),
  382. 'PV_PCS_FX' => new Expression('PV_PCS_FX+' . $data['PV_PCS_FX']),
  383. 'PV_PSS' => new Expression('PV_PSS+' . $data['PV_PSS']),
  384. 'PV_PSS_TOTAL' => new Expression('PV_PSS_TOTAL+' . $data['PV_PSS']),
  385. 'PV_1L' => new Expression('PV_1L+' . $data['PV_1L']),
  386. 'PV_2L' => new Expression('PV_2L+' . $data['PV_2L']),
  387. 'PV_3L' => new Expression('PV_3L+' . $data['PV_3L']),
  388. 'PV_4L' => new Expression('PV_4L+' . $data['PV_4L']),
  389. 'PV_5L' => new Expression('PV_5L+' . $data['PV_5L']),
  390. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  391. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  392. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  393. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  394. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  395. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  396. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  397. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  398. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  399. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  400. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  401. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  402. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  403. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  404. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  405. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  406. }
  407. } else {
  408. $isUpdate = true;
  409. UserPerf::insertOne([
  410. 'USER_ID' => $data['USER_ID'],
  411. 'PV_PCS_ZC' => $data['PV_PCS_ZC'],
  412. 'PV_PCS_YH' => $data['PV_PCS_YH'],
  413. 'PV_PCS_ZG' => $data['PV_PCS_ZG'],
  414. 'PV_PCS_LS' => $data['PV_PCS_LS'],
  415. 'PV_PCS_FX' => $data['PV_PCS_FX'],
  416. 'PV_PSS' => $data['PV_PSS'],
  417. 'PV_PSS_TOTAL' => $data['PV_PSS'],
  418. 'PV_1L' => $data['PV_1L'],
  419. 'PV_2L' => $data['PV_2L'],
  420. 'PV_3L' => $data['PV_3L'],
  421. 'PV_4L' => $data['PV_4L'],
  422. 'PV_5L' => $data['PV_5L'],
  423. 'SURPLUS_1L' => $data['SURPLUS_1L'],
  424. 'SURPLUS_2L' => $data['SURPLUS_2L'],
  425. 'SURPLUS_3L' => $data['SURPLUS_3L'],
  426. 'SURPLUS_4L' => $data['SURPLUS_4L'],
  427. 'SURPLUS_5L' => $data['SURPLUS_5L'],
  428. 'SURPLUS_1L_ZC' => $data['SURPLUS_1L_ZC'],
  429. 'SURPLUS_2L_ZC' => $data['SURPLUS_2L_ZC'],
  430. 'SURPLUS_3L_ZC' => $data['SURPLUS_3L_ZC'],
  431. 'SURPLUS_4L_ZC' => $data['SURPLUS_4L_ZC'],
  432. 'SURPLUS_5L_ZC' => $data['SURPLUS_5L_ZC'],
  433. 'SURPLUS_1L_FX' => $data['SURPLUS_1L_FX'],
  434. 'SURPLUS_2L_FX' => $data['SURPLUS_2L_FX'],
  435. 'SURPLUS_3L_FX' => $data['SURPLUS_3L_FX'],
  436. 'SURPLUS_4L_FX' => $data['SURPLUS_4L_FX'],
  437. 'SURPLUS_5L_FX' => $data['SURPLUS_5L_FX'],
  438. 'CREATED_AT' => Date::nowTime(),
  439. ]);
  440. }
  441. if ($isUpdate) {
  442. // 变为已更新
  443. UserPerfUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'PERIOD_NUM' => $this->_periodNum, 'P_CALC_MONTH' => Date::ociToDate($this->_calcYearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH), 'CREATED_AT' => Date::nowTime()]);
  444. }
  445. unset($data, $isUpdate);
  446. }
  447. $transaction->commit();
  448. } catch (Exception $e) {
  449. $transaction->rollBack();
  450. $this->addError('updateUserPerf', '更新会员业绩失败,原因:' . $e->getMessage());
  451. return false;
  452. }
  453. unset($allData, $transaction);
  454. return $this->updateUserPerf($offset + $this->_limit);
  455. }
  456. unset($allData);
  457. return true;
  458. }
  459. /**
  460. * 更新会员的月剩余业绩
  461. * @param int $offset
  462. * @return bool
  463. * @throws \yii\db\Exception
  464. */
  465. public function updateUserPerfMonth(int $offset = 0) {
  466. // 月结,如果不是月结点,则直接退出
  467. if (!$this->_isCalcMonth) {
  468. return true;
  469. }
  470. $allData = PerfMonth::findUseDbCalc()->where('CALC_MONTH=:CALC_MONTH', [':CALC_MONTH' => $this->_calcYearMonth])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->all();
  471. if ($allData) {
  472. $transaction = Yii::$app->db->beginTransaction();
  473. try {
  474. foreach ($allData as $data) {
  475. $isUpdate = false;
  476. if (UserPerf::findUseDbCalc()->where('USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']])->exists()) {
  477. // 判断本期是否已经更新过业绩
  478. if (!UserPerfMonthUpdate::findUseDbCalc()->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID' => $data['USER_ID'], ':CALC_MONTH' => $this->_calcYearMonth])->exists()) {
  479. $isUpdate = true;
  480. // 更新业绩
  481. UserPerf::updateAll([
  482. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  483. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  484. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  485. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  486. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC']
  487. ], 'USER_ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
  488. }
  489. } else {
  490. $isUpdate = true;
  491. UserPerf::insertOne([
  492. 'USER_ID' => $data['USER_ID'],
  493. 'VIP_SURPLUS_1L_ZC' => $data['VIP_SURPLUS_1L_ZC'],
  494. 'VIP_SURPLUS_2L_ZC' => $data['VIP_SURPLUS_2L_ZC'],
  495. 'VIP_SURPLUS_3L_ZC' => $data['VIP_SURPLUS_3L_ZC'],
  496. 'VIP_SURPLUS_4L_ZC' => $data['VIP_SURPLUS_4L_ZC'],
  497. 'VIP_SURPLUS_5L_ZC' => $data['VIP_SURPLUS_5L_ZC'],
  498. 'CREATED_AT' => Date::nowTime(),
  499. ]);
  500. }
  501. if ($isUpdate) {
  502. // 变为已更新
  503. UserPerfMonthUpdate::insertOne(['USER_ID' => $data['USER_ID'], 'CALC_MONTH' => $this->_calcYearMonth, 'CREATED_AT' => Date::nowTime()]);
  504. }
  505. unset($data, $isUpdate);
  506. }
  507. $transaction->commit();
  508. } catch (Exception $e) {
  509. $transaction->rollBack();
  510. $this->addError('updateUserPerf', '更新会员月业绩失败,原因:' . $e->getMessage());
  511. return false;
  512. }
  513. unset($allData, $transaction);
  514. return $this->updateUserPerfMonth($offset + $this->_limit);
  515. }
  516. unset($allData);
  517. return true;
  518. }
  519. /**
  520. * 检测复消积分是否过期
  521. * @return bool
  522. * @throws \yii\db\Exception
  523. */
  524. public function checkReconsumePointsExpired(int $offset = 0) {
  525. $periodNum = $this->_periodNum;
  526. //一期为7天,那么365天为52.14即53期
  527. $expiredPeriodNum = $periodNum - 53;
  528. if( $expiredPeriodNum <= 0 ) return true;
  529. //查询需要过期的期数
  530. $allData = UserPeriodPoints::find()->select('ID,USER_ID,REMAINDER_POINTS')->where('PERIOD_NUM<=:PERIOD_NUM AND EXPIRED=0', ['PERIOD_NUM'=>$expiredPeriodNum])->orderBy('ID ASC')->offset($offset)->limit($this->_limit)->asArray()->all();
  531. if( $allData ) {
  532. $transaction = Yii::$app->db->beginTransaction();
  533. try{
  534. //扣除钱包的复消积分
  535. foreach ($allData as $everyData) {
  536. //过期
  537. UserPeriodPoints::updateAll([
  538. 'REMAINDER_POINTS' => 0,
  539. 'EXPIRED' => 1,
  540. 'EXPIRED_PERIOD' => $periodNum,
  541. 'EXPIRED_AT' => Date::nowTime(),
  542. ], 'ID=:ID', ['ID'=>$everyData['ID']]);
  543. if( !isset($everyData['REMAINDER_POINTS']) || !$everyData['REMAINDER_POINTS'] ) continue;
  544. UserBonus::updateAllCounters([
  545. 'RECONSUME_POINTS' => (-1) * $everyData['REMAINDER_POINTS'],
  546. ], 'USER_ID=:USER_ID', $everyData['USER_ID']);
  547. unset($everyData);
  548. }
  549. unset($periodNum, $expiredPeriodNum, $allData);
  550. $transaction->commit();
  551. }catch (\Exception $e){
  552. $transaction->rollBack();
  553. $this->addError('checkReconsumePointsExpired', '检测过期在复消积分失败,原因:' . $e->getMessage());
  554. return false;
  555. }
  556. return $this->checkReconsumePointsExpired($offset + $this->_limit);
  557. }
  558. unset($allData);
  559. return true;
  560. }
  561. /**
  562. * 更新会员上次报单级别
  563. * @return bool
  564. */
  565. public function updateUserDevLv() {
  566. $transaction = Yii::$app->dbShop->beginTransaction();
  567. try {
  568. \Yii::$app->dbShop->createCommand()->update(User::tableName(), ['LAST_DEC_LV' => new Expression('DEC_LV'), 'LAST_DEC_LV_UPDATED_AT' => Date::nowTime(), 'LAST_DEC_LV_UPDATED_PERIOD' => $this->_periodNum], 'LAST_DEC_LV!=DEC_LV')->execute();
  569. $transaction->commit();
  570. } catch (Exception $e) {
  571. $transaction->rollBack();
  572. $this->addError('updateUserDevLv', '更新会员上次报单级别失败,原因:' . $e->getMessage());
  573. return false;
  574. }
  575. return true;
  576. }
  577. /**
  578. * 给商城会员增加货款
  579. * @param $userId
  580. * @param $amount
  581. * @param $remark
  582. * @throws Exception
  583. */
  584. private function _shopAddPaymentForGoods($userId, $amount, $remark) {
  585. $db = \Yii::$app->dbShop;
  586. $transaction = $db->beginTransaction();
  587. try {
  588. ActiveRecord::batchUpdate(['PAYMENT_FOR_GOODS' => new Expression('PAYMENT_FOR_GOODS+' . abs($amount))], 'USER_ID=:USER_ID', [':USER_ID' => $userId], '{{%USER_WALLET}}', 'dbShop');
  589. // 增加流水
  590. $flowInsertData[] = [
  591. 'USER_ID' => $userId,
  592. 'USER_NAME' => Cache::getUserBaseInfo($userId)['USER_NAME'],
  593. 'DEC_LV' => Cache::getUserBaseInfo($userId)['DEC_LV'],
  594. 'ORDER_SN' => null,
  595. 'AMOUNT' => $amount,
  596. 'CREATED_AT' => Date::nowTime(),
  597. 'PERIOD_AT' => $this->_periodNum,
  598. 'IS_INCR' => 1,
  599. 'REMARK' => $remark,
  600. 'PARTITION_DATE' => Date::ociToDate(),
  601. 'WALLET_TYPE' => 'payment_for_goods',
  602. 'FROM_TYPE' => 'incr',
  603. ];
  604. ActiveRecord::batchInsert($flowInsertData, '{{%FLOW_WALLET}}', 'dbShop');
  605. $transaction->commit();
  606. } catch (Exception $e) {
  607. $transaction->rollBack();
  608. throw new Exception($e->getMessage());
  609. }
  610. }
  611. /**
  612. * 更新百分比并发送
  613. * @param $percent
  614. */
  615. private function _updatePercent($percent) {
  616. // 把数据写入数据库中
  617. Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $this->_periodNum]);
  618. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $this->_periodId, 'FIELD' => 'SENT_PERCENT']);
  619. }
  620. /**
  621. * 更新最高聘级
  622. * @param $user_id
  623. * @return bool
  624. * @throws Exception
  625. */
  626. private function _updateHighestEmpLv($user_id) {
  627. $empLv = Info::getEmpLv($user_id);
  628. $highEmpLv = Info::getHighEmpLv($user_id);
  629. $empLvSort = EmployLevel::getSortById($empLv);
  630. $empLvHighSort = EmployLevel::getSortById($highEmpLv);
  631. if ($empLvHighYear = YearHighestEmpLv::findOneAsArray('USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear], 'HIGHEST_EMP_LV_SORT')) {
  632. if ($empLvSort > $empLvHighYear['HIGHEST_EMP_LV_SORT']) {
  633. YearHighestEmpLv::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_SORT' => $empLvSort, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum, 'UPDATED_AT' => Date::nowTime()], 'USER_ID=:USER_ID AND YEAR=:YEAR', [':USER_ID' => $user_id, ':YEAR' => $this->_calcYear]);
  634. }
  635. } else {
  636. $yearHighest = new YearHighestEmpLv();
  637. $yearHighest->USER_ID = $user_id;
  638. $yearHighest->YEAR = $this->_calcYear;
  639. $yearHighest->HIGHEST_EMP_LV = $empLv;
  640. $yearHighest->HIGHEST_EMP_LV_SORT = $empLvSort;
  641. $yearHighest->HIGHEST_EMP_LV_PERIOD = $this->_periodNum;
  642. $yearHighest->CREATED_AT = Date::nowTime();
  643. if (!$yearHighest->save()) {
  644. throw new \yii\db\Exception(Form::formatErrorsForApi($yearHighest->getErrors()));
  645. }
  646. }
  647. if ($empLvSort > $empLvHighSort) {
  648. UserInfo::updateAll(['HIGHEST_EMP_LV' => $empLv, 'HIGHEST_EMP_LV_PERIOD' => $this->_periodNum], 'USER_ID=:USER_ID', [':USER_ID' => $user_id]);
  649. //发送历史最高聘级短信
  650. if($this->_sysConfig['smsEmpOpen']['VALUE']){
  651. if(in_array($empLvSort,explode(",",$this->_sysConfig['smsEmp']['VALUE']))){
  652. $realName = Info::getUserRealNameByUserId($user_id);
  653. $empLvDate = Date::convert();
  654. $empLvName = EmployLevel::getNameById($empLv);
  655. $content = str_replace(['{%REAL_NAME%}', '{%EMP_LV_DATE%}', '{%EMP_LV%}'], [$realName, $empLvDate, $empLvName], $this->_sysConfig['smsContent']['VALUE']);
  656. $params = [
  657. 'mobiles' => Info::getUserMobileByUserId($user_id),
  658. 'content' => $content,
  659. ];
  660. SmsApi::instance()->clearError();
  661. SmsApi::instance()->goSend($params);
  662. }
  663. }
  664. return true;
  665. }
  666. return false;
  667. }
  668. /**
  669. * 点位合作奖金
  670. * @param $userId
  671. * @param $amount
  672. * @param null $type
  673. * @return bool
  674. * @throws Exception
  675. * @throws \yii\db\Exception
  676. */
  677. private function _teamworkBonus($userId, $amount, $key) {
  678. if (!$teamwork = UserTeamwork::findAllAsArray('USER_ID!=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userId], 'USER_ID,DIVIDE_PERCENT')) return false;
  679. $fromUserInfo = CalcCache::getUserInfo($userId, $this->_periodNum);
  680. foreach ($teamwork as $value) {
  681. $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
  682. if ($bonus <= 0) continue;
  683. $toUserInfo = CalcCache::getUserInfo($value['USER_ID'], $this->_periodNum);
  684. Balance::changeUserBonus($userId, 'bonus', -abs($bonus), ['SORT' => $key*10+1, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_OUT, 'REMARK' => 'To:' . $toUserInfo['USER_NAME'] . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
  685. Balance::changeUserBonus($value['USER_ID'], 'bonus', abs($bonus), ['SORT' => $key*10+2, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_IN, 'REMARK' => 'From: ' . $fromUserInfo['USER_NAME'] . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
  686. }
  687. }
  688. /**
  689. * 发送短信
  690. * @param int $offset
  691. * @return bool
  692. * @throws \yii\db\Exception
  693. */
  694. public function sendSmsLoop(int $offset = 0) {
  695. $allData = UserInfo::findUseDbCalc()->select('USER_ID,ALLOW_RECONSUME_SMS_TO')->where('ALLOW_RECONSUME_SMS=1')->offset($offset)->limit($this->_limit)->all();
  696. if ($allData) {
  697. $smsWallet = explode(",", $this->_sysConfig['smsWallet']['VALUE']);
  698. $smsFee = $this->_sysConfig['smsFee']['VALUE'];
  699. //获取剩余月份
  700. $period = Period::instance();
  701. $year = $period->getYear($this->_periodNum);
  702. $monthLeft = Period::getMonthLeft($this->_periodNum);
  703. $smsFee = Tool::formatPrice($smsFee * $monthLeft);
  704. $to = Date::yearEnd();
  705. $transaction = Yii::$app->db->beginTransaction();
  706. try {
  707. foreach ($allData as $data) {
  708. $userId = $data['USER_ID'];
  709. //过期续费
  710. if ($data['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
  711. foreach ($smsWallet as $item) {
  712. //1奖金钱包2现金钱包
  713. if ($item == 1) {
  714. //看余额是否充足
  715. if (Balance::getAvailableBalance($userId) < $smsFee){
  716. UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  717. continue;
  718. };
  719. Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费'], false);
  720. UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
  721. $data['ALLOW_RECONSUME_SMS_TO'] = $to;
  722. break;
  723. } elseif ($item == 2) {
  724. throw new Exception('不存在此方式');
  725. break;
  726. }
  727. }
  728. }
  729. if ($data['ALLOW_RECONSUME_SMS_TO'] > Date::nowTime() && $mobile = Info::getUserMobileByUserId($userId)) {
  730. $realName = Info::getUserRealNameByUserId($userId);
  731. $reconsumPool = Reconsume::getUserReconsumePool($userId);
  732. $lastRechargeDate = $reconsumPool['toRechargeDate'];
  733. $isPass = $reconsumPool['isPass'] == 1 ? '合格' : '不合格';
  734. $month = $period->getNowMonth();
  735. $content = str_replace(['{%REAL_NAME%}', '{%LAST_RECHARGE_DATE%}', '{%MONTH%}', '{%IS_PASS%}'], [$realName, $lastRechargeDate, $month, $isPass], $this->_sysConfig['smsContent']['VALUE']);
  736. //todo 发短信函数 待测试
  737. $params = [
  738. 'mobiles' => $mobile,
  739. 'content' => $content,
  740. ];
  741. SmsApi::instance()->clearError();
  742. SmsApi::instance()->goSend($params);
  743. }
  744. unset($userId,$mobile,$realName,$reconsumPool,$lastRechargeDate,$isPass,$month,$content);
  745. }
  746. $transaction->commit();
  747. } catch (Exception $e) {
  748. $transaction->rollBack();
  749. return false;
  750. }
  751. unset($data);
  752. return $this->sendSmsLoop($offset + $this->_limit);
  753. }
  754. unset($allData);
  755. return true;
  756. }
  757. }