WithdrawForm.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. <?php
  2. namespace common\models\forms;
  3. use common\components\Model;
  4. use common\helpers\Cache;
  5. use common\helpers\Date;
  6. use common\helpers\Form;
  7. use common\helpers\Tool;
  8. use common\helpers\user\Balance;
  9. use common\helpers\user\Info;
  10. use common\helpers\user\Status;
  11. use common\libs\logging\operate\UserOperate;
  12. use common\models\CompanyBank;
  13. use common\models\DealType;
  14. use common\models\DecOrder;
  15. use common\models\InvoiceAudit;
  16. use common\models\Order;
  17. use common\models\PerfPeriod;
  18. use common\models\Period;
  19. use common\models\RegType;
  20. use common\models\User;
  21. use common\models\UserBonus;
  22. use common\models\UserInfo;
  23. use common\models\UserRelation;
  24. use common\models\UserTeamwork;
  25. use common\models\Withdraw;
  26. use common\models\WithdrawLevel;
  27. use common\helpers\http\LingYunGongApi;
  28. use yii\base\Exception;
  29. /**
  30. * Login form
  31. */
  32. class WithdrawForm extends Model {
  33. public $id;
  34. public $selectedIds;
  35. public $userName;
  36. public $realName;
  37. public $idCard;
  38. public $regType;
  39. public $applyAmount;
  40. public $payPassword;
  41. public $auditStatus;
  42. public $planPaidAt;
  43. public $createdAt;
  44. public $createRemark;
  45. public $withdrawCode;
  46. public $withdrawAudit;
  47. public $sn;
  48. public $withdrawPeriodNum;
  49. public $paidAt;
  50. public $paidFailRemark;
  51. public $amount;
  52. public $bankRealName;
  53. public $bankNo;
  54. private $_userId;
  55. public function init() {
  56. parent::init();
  57. $this->userOperateLogger = new UserOperate([
  58. 'fetchClass' => Withdraw::class,
  59. ]);
  60. }
  61. /**
  62. * @inheritdoc
  63. */
  64. public function rules() {
  65. return [
  66. [['id', 'userName', 'realName', 'idCard', 'regType', 'applyAmount', 'payPassword', 'planPaidAt', 'auditStatus', 'createdAt', 'remark', 'createRemark', 'selectedIds', 'sn', 'withdrawPeriodNum', 'paidAt', 'paidFailRemark', 'amount', 'bankRealName', 'bankNo'], 'trim'],
  67. [['id', 'userName', 'applyAmount', 'payPassword', 'auditStatus','withdrawCode','withdrawAudit'], 'required'],
  68. [['id'], 'exist', 'targetClass' => Withdraw::class, 'targetAttribute' => 'ID', 'message' => '提现申请不存在'],
  69. [['userName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME', 'message' => '会员不存在'],
  70. [['applyAmount'], 'price'],
  71. [['applyAmount'], 'isApplyAmount'],
  72. [['userName'], 'isUserName'],
  73. [['payPassword'], 'validatePassword'],
  74. [['withdrawCode'], 'validateCode'],
  75. [['withdrawAudit'], 'validateAuditCode'],
  76. [['planPaidAt'], 'isPlanPaidAt'],
  77. [['selectedIds'], 'isSelected'],
  78. [['sn'], 'isSn'],
  79. //[['auditStatus'], 'isStatus'],
  80. ];
  81. }
  82. /**
  83. * 指定场景
  84. * @return array
  85. */
  86. public function scenarios() {
  87. $parentScenarios = parent::scenarios();
  88. $customScenarios = [
  89. 'addByAdmin' => ['userName', 'realName', 'idCard', 'regType', 'applyAmount', 'createRemark'],
  90. 'addByUser' => ['applyAmount', 'payPassword','withdrawCode'],
  91. 'addByAuto' => ['userName', 'applyAmount'],
  92. 'statusByAdmin' => ['selectedIds', 'auditStatus', 'createRemark','planPaidAt', 'paidAt','withdrawAudit'],
  93. 'editByAdmin' => ['id', 'planPaidAt', 'createRemark'],
  94. 'backByUser' => ['id', 'createRemark'],
  95. 'excelPaidFalse' => ['sn', 'withdrawPeriodNum', 'paidAt', 'paidFailRemark', 'userName', 'realName', 'amount', 'bankRealName', 'bankNo'],
  96. ];
  97. return array_merge($parentScenarios, $customScenarios);
  98. }
  99. /**
  100. * @return array
  101. */
  102. public function attributeLabels() {
  103. return [
  104. 'id' => '提现申请ID',
  105. 'userName' => '会员编号',
  106. 'applyAmount' => '申请提现的金额',
  107. 'withdrawCode' => '申请提现校验码',
  108. 'withdrawAudit' => '提现审核校验码',
  109. ];
  110. }
  111. /**
  112. * 用户名是否正确
  113. * @param $attributes
  114. * @throws Exception
  115. */
  116. public function isUserName($attributes) {
  117. $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
  118. if ($userInfo) {
  119. if ($this->scenario == 'addByAdmin') {
  120. $baseInfo = Info::baseInfoZh($userInfo['USER_ID']);
  121. if ($baseInfo['REAL_NAME'] != $this->realName || $baseInfo['ID_CARD'] != $this->idCard) {
  122. $this->addError($attributes, '输入的会员姓名或身份证号与系统不一致');
  123. }
  124. if ($userInfo['REG_TYPE'] != $this->regType) {
  125. $this->addError($attributes, '选择的会员注册类型与系统不一致');
  126. }
  127. }
  128. $this->_userId = $userInfo['USER_ID'];
  129. } else {
  130. $this->addError($attributes, $this->userName . '会员不存在');
  131. }
  132. }
  133. /**
  134. * 校验申请金额是否小于当前余额并符合配置中的设置
  135. * @param $attribute
  136. * @return bool
  137. */
  138. public function isApplyAmount($attribute) {
  139. $config = Cache::getSystemConfig();
  140. if ($this->applyAmount <= 0) {
  141. $this->addError('scenario', '提现金额必须大于0');
  142. }
  143. if ((int)($this->applyAmount)!=$this->applyAmount) {
  144. $this->addError('scenario', '提现金额必须是整数');
  145. }
  146. $minAmount = 0;
  147. $maxAmount = 0;
  148. if ($this->scenario == 'addByUser') {
  149. $minAmount = $config['manualWithdrawMinAmount']['VALUE'];
  150. // $maxAmount = $config['manualWithdrawMaxAmount']['VALUE'];
  151. $this->_userId = \Yii::$app->user->id;
  152. } elseif ($this->scenario == 'addByAdmin') {
  153. $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
  154. $this->_userId = $userInfo['USER_ID'];
  155. } else {
  156. $this->addError($attribute, '场景不存在');
  157. return false;
  158. }
  159. if ($minAmount != 0 && $this->applyAmount < $minAmount) {
  160. $this->addError($attribute, '提现金额不能少于' . $minAmount . '元');
  161. }
  162. if ($maxAmount != 0 && $this->applyAmount > $maxAmount) {
  163. $this->addError($attribute, '提现金额不能高于' . $maxAmount . '元');
  164. }
  165. // 提现条件判断
  166. $orderAmount = Order::find()->where('USER_ID=:USER_ID', [':USER_ID' => $this->_userId])->SUM('ORDER_AMOUNT');
  167. $recNum = intval(DecOrder::find()->where('REC_USER_ID=:REC_USER_ID', [':REC_USER_ID' => $this->_userId])->count());
  168. //$recNum = UserRelation::firstFloorChildNum($this->_userId);
  169. // if ($orderAmount < 300 && $recNum==0) {
  170. // $this->addError($attribute, '奖金不能提现');
  171. // return null;
  172. // }
  173. // 获取当前提现用户的金额
  174. if ($this->applyAmount > Balance::getAvailableBalance($this->_userId)) {
  175. $this->addError('scenario', '提现金额必须小于的可用余额');
  176. }
  177. }
  178. /**
  179. * 校验支付密码
  180. * @param $attribute
  181. * @param $params
  182. */
  183. public function validatePassword($attribute, $params) {
  184. if (!User::validatePayPassword($this->_userId, $this->payPassword)) {
  185. $this->addError($attribute, '支付密码不正确');
  186. }
  187. }
  188. public function validateCode($attribute) {
  189. $uid = \Yii::$app->user->id;
  190. $redisCode = \Yii::$app->redis->getset('withdrawCode_'.$uid,'');
  191. \Yii::$app->redis->del('withdrawCode_'.$uid);
  192. if ($this->withdrawCode!=$redisCode) {
  193. $this->addError($attribute, '申请提现校验失败');
  194. }
  195. }
  196. public function validateAuditCode($attribute) {
  197. $adminId = \Yii::$app->user->id;
  198. $redisCode = \Yii::$app->redis->getset('withdrawAudit_'.$adminId,'');
  199. if ($this->withdrawAudit!=$redisCode) {
  200. $this->addError($attribute, '提现审核校验失败');
  201. }
  202. }
  203. /**
  204. * 批量数据
  205. * @param $attributes
  206. */
  207. public function isSelected($attributes) {
  208. if (!$this->selectedIds) {
  209. $this->addError($attributes, '必须选择一条数据');
  210. }
  211. if (!is_array($this->selectedIds)) {
  212. $this->selectedIds = [$this->selectedIds];
  213. }
  214. }
  215. /**
  216. * 校验状态
  217. * @param $attribute
  218. */
  219. public function isStatus($attribute) {
  220. }
  221. /**
  222. * 计划付款日期
  223. * @param $attribute
  224. */
  225. public function isPlanPaidAt($attribute) {
  226. if (Date::utcToTime($this->planPaidAt) < Date::nowTime()) {
  227. $this->addError($attribute, '不能选择过去的日期');
  228. }
  229. }
  230. /**
  231. * 判断信息是否一致
  232. * @param $attribute
  233. * @throws Exception
  234. */
  235. public function isSn($attribute) {
  236. $sn = $this->sn;
  237. if (!$oneWithdraw = Withdraw::findOneAsArray('SN=:SN AND AUDIT_STATUS=:AUDIT_STATUS', [':SN' => $sn, ':AUDIT_STATUS' => Withdraw::STATUS_PAID])) {
  238. $this->addError($attribute, '不存在提现流水号为' . $sn . '的已付款记录');
  239. }
  240. if ($oneWithdraw) {
  241. $info = Info::baseInfo($oneWithdraw['USER_ID']);
  242. if ($this->userName != $info['USER_NAME']) {
  243. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的用户名' . $this->userName . '与系统中的信息【' . $info['USER_NAME'] . '】不一致');
  244. }
  245. if ($this->realName != $info['REAL_NAME']) {
  246. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的会员姓名' . $this->realName . '与系统中的信息【' . $info['REAL_NAME'] . '】不一致');
  247. }
  248. if ($this->withdrawPeriodNum != $oneWithdraw['WITHDRAW_PERIOD_NUM']) {
  249. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的提现期数' . $this->withdrawPeriodNum . '与系统中的信息【' . $oneWithdraw['WITHDRAW_PERIOD_NUM'] . '】不一致');
  250. }
  251. if (Date::convert(Date::utcToTime($this->paidAt)) != Date::convert($oneWithdraw['PAID_AT'])) {
  252. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的付款日期' . Date::convert(Date::utcToTime($this->paidAt)) . '与系统中的信息【' . Date::convert($oneWithdraw['PAID_AT']) . '】不一致');
  253. }
  254. if ($this->amount != $oneWithdraw['AMOUNT']) {
  255. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的提现金额' . $this->amount . '与系统中的信息【' . $oneWithdraw['AMOUNT'] . '】不一致');
  256. }
  257. if ($this->bankRealName != $oneWithdraw['REAL_NAME']) {
  258. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的实时开户名' . $this->bankRealName . '与系统中的信息【' . $oneWithdraw['REAL_NAME'] . '】不一致');
  259. }
  260. if ($this->bankNo != $oneWithdraw['BANK_NO']) {
  261. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的实时银行账户' . $this->bankNo . '与系统中的信息【' . $oneWithdraw['BANK_NO'] . '】不一致');
  262. }
  263. }
  264. }
  265. /**
  266. * 添加提现申请
  267. * @return null|string
  268. * @throws \yii\db\Exception
  269. */
  270. public function add() {
  271. if (!$this->validate()) {
  272. return false;
  273. }
  274. $beforeData = Balance::getLogData(\Yii::$app->user->id);
  275. $this->userOperateLogger->saveBeforeContent=$beforeData;
  276. $config = Cache::getSystemConfig();
  277. $db = \Yii::$app->db;
  278. $transaction = $db->beginTransaction();
  279. try {
  280. $nowTime = $this->createdAt ? $this->createdAt : Date::nowTime();
  281. $period = Withdraw::getPeriod($nowTime);
  282. //扣除会员奖金
  283. Balance::changeUserBonus($this->_userId, 'BONUS', -abs($this->applyAmount), ['DEAL_TYPE_ID'=>DealType::WITHDRAW,'REMARK' => $period['nowPeriodNum'].'期'.($this->scenario == 'addByAuto' ? '自动提现' : '手动提现'), 'TIME' => $nowTime]);
  284. //增加记录
  285. $userInfo = Info::baseInfo($this->_userId);
  286. //手续费
  287. $fees = $this->applyAmount * $config['withdrawFee']['VALUE']/100;
  288. $fees = Tool::formatPrice($fees);
  289. $realAmount = $this->applyAmount - $fees;
  290. //判断付款类型
  291. $payType = Withdraw::PAY_TYPE_NO_INVOICE;
  292. $withdrawModel = new Withdraw();
  293. $withdrawModel->SN = $this->_generateSn();
  294. $withdrawModel->USER_ID = $this->_userId;
  295. $withdrawModel->ID_CARD = $userInfo['ID_CARD'];
  296. $withdrawModel->WITHDRAW_PERIOD_NUM = $period['nowPeriodNum'];
  297. $withdrawModel->WITHDRAW_YEAR = $period['nowYear'];
  298. $withdrawModel->WITHDRAW_MONTH = $period['nowMonth'];
  299. $withdrawModel->PAY_TYPE = $payType;
  300. $withdrawModel->IS_AUTO_WITHDRAW = $this->scenario == 'addByAuto' ? 1 : 0;
  301. $withdrawModel->AMOUNT = $this->applyAmount;
  302. $withdrawModel->FEES = $fees;
  303. $withdrawModel->REAL_AMOUNT = $realAmount;
  304. $withdrawModel->P_MONTH = Date::ociToDate($period['yearMonth'], Date::OCI_TIME_FORMAT_SHORT_MONTH);
  305. // if ($payType == Withdraw::PAY_TYPE_NO_INVOICE) {
  306. // $withdrawModel->AUDIT_STATUS = Withdraw::STATUS_AUDITED;
  307. // $withdrawModel->AUDITED_AT = $nowTime;
  308. // } else {
  309. $withdrawModel->AUDIT_STATUS = Withdraw::STATUS_APPLIED;
  310. // }
  311. $withdrawModel->CREATED_AT = $nowTime;
  312. //预计付款时间
  313. $withdrawModel->PLAN_PAID_AT = $period['endTime'] + $config['withdrawFreezeDays']['VALUE'] * 3600 * 24;
  314. if ($this->scenario == 'addByAdmin') {
  315. $withdrawModel->UPDATE_ADMIN = \Yii::$app->user->id;
  316. $withdrawModel->UPDATE_REMARK = $this->createRemark;
  317. }
  318. if (!$withdrawModel->save()) {
  319. throw new Exception(Form::formatErrorsForApi($withdrawModel->getErrors()));
  320. }
  321. //考核会员注册类型
  322. // RegType::chkRegType($this->_userId, $userInfo['SHOULD_REG_TYPE'], $period['nowYear'], $period['nowMonth']);
  323. $transaction->commit();
  324. } catch (Exception $e) {
  325. $transaction->rollBack();
  326. $this->addError('add', $e->getMessage());
  327. return false;
  328. }
  329. $afterData = Balance::getLogData(\Yii::$app->user->id);
  330. $this->userOperateLogger->saveAfterContent=$afterData;
  331. unset($beforeData,$afterData);
  332. $this->userOperateLogger->clean()->save([
  333. 'optType' => '会员提现申请',
  334. 'userId' => \Yii::$app->user->id,
  335. 'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
  336. 'remark' => $this->createRemark,
  337. ]);
  338. return $withdrawModel;
  339. }
  340. /**
  341. * 检测是否上传身份证
  342. * @return int
  343. */
  344. public function checkHasIdCardInfo() {
  345. if ($this->scenario !== 'addByUser') return 0;
  346. $userId = \Yii::$app->user->id;
  347. $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,ID_CARD');
  348. if( !$user ) {
  349. $this->addError('add', '不存在该用户');
  350. return -1;
  351. }
  352. if( !$user['ID_CARD'] ) {
  353. $this->addError('add', '完善身份信息后才可以提现');
  354. return -1;
  355. }
  356. $response = LingYunGongApi::hasIdCardInfo($user['ID_CARD']);
  357. if( !$response ) {
  358. $this->addError('add', '接口网络错误');
  359. return -1;
  360. }
  361. if( !isset($response['has']) ) {
  362. $this->addError('add', '接口格式错误');
  363. return -1;
  364. }
  365. if( $response['has'] === true ) {
  366. return 0;
  367. }else {
  368. $this->addError('add', $response['err_msg']['msg']);
  369. return -2;
  370. }
  371. }
  372. /**
  373. * 生成流水号
  374. * @return string
  375. */
  376. private function _generateSn() {
  377. return 'TX' . Date::today('Ymd') . $this->_random(10, 1);
  378. }
  379. /**
  380. * 生成随机数
  381. *
  382. * @param $length
  383. * @param int $numeric
  384. * @return string
  385. */
  386. private function _random($length, $numeric = 0) {
  387. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  388. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  389. $hash = '';
  390. $max = strlen($seed) - 1;
  391. for ($i = 0; $i < $length; $i++) {
  392. $hash .= $seed[mt_rand(0, $max)];
  393. }
  394. return $hash;
  395. }
  396. /**
  397. * 生成随机数
  398. * @param $length
  399. * @param int $numeric
  400. * @return string
  401. */
  402. public function wdcode($length, $numeric = 0) {
  403. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  404. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  405. $hash = '';
  406. $max = strlen($seed) - 1;
  407. for ($i = 0; $i < $length; $i++) {
  408. $hash .= $seed[mt_rand(0, $max)];
  409. }
  410. return $hash;
  411. }
  412. /**
  413. * 修改预计打款日期
  414. * @return null|static
  415. * @throws \yii\db\Exception
  416. */
  417. public function editByAdmin() {
  418. if (!$this->validate()) {
  419. return null;
  420. }
  421. $db = \Yii::$app->db;
  422. $transaction = $db->beginTransaction();
  423. try {
  424. $oneWithdraw = Withdraw::findOne(['ID' => $this->id]);
  425. $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
  426. $oneWithdraw->REMARK = $this->createRemark;
  427. $planPaidAt = Date::utcToTime($this->planPaidAt);
  428. if ($oneWithdraw->PLAN_PAID_AT != $planPaidAt) {
  429. $oneWithdraw->PLAN_PAID_AT = $planPaidAt;
  430. }
  431. if (!$oneWithdraw->save()) {
  432. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  433. }
  434. $transaction->commit();
  435. } catch (Exception $e) {
  436. $transaction->rollBack();
  437. $this->addError('status', $e->getMessage());
  438. return null;
  439. }
  440. return $oneWithdraw;
  441. }
  442. /**
  443. * 前台提现退回
  444. * @return null|static
  445. * @throws \yii\db\Exception
  446. */
  447. public function backByUser() {
  448. if (!$this->validate()) {
  449. return null;
  450. }
  451. $oneWithdraw = Withdraw::findOne(['ID' => $this->id]);
  452. $db = \Yii::$app->db;
  453. $transaction = $db->beginTransaction();
  454. try {
  455. if (Cache::getSystemConfig()['isCanWithdrawBack']['VALUE'] != 1) {
  456. throw new Exception('提现退回已关闭');
  457. }
  458. if (!Withdraw::find()->where('USER_ID=:USER_ID AND ID=:ID AND AUDIT_STATUS=:AUDIT_STATUS_1', ['USER_ID' => \Yii::$app->user->id, ':ID' => $this->id, ':AUDIT_STATUS_1' => Withdraw::STATUS_APPLIED])->exists()) {
  459. throw new Exception('符合退回的提现记录不存在');
  460. }
  461. $oneWithdraw->BACK_REMARK = $this->createRemark;
  462. $oneWithdraw->BACK_FAIL_AT = Date::nowTime();
  463. $oneWithdraw->AUDIT_STATUS = Withdraw::STATUS_RETURN;
  464. Balance::changeUserBonus($oneWithdraw['USER_ID'], 'BONUS', abs($oneWithdraw['AMOUNT']), ['DEAL_TYPE_ID'=>DealType::WITHDRAW_RETURN,'REMARK' => $oneWithdraw->WITHDRAW_PERIOD_NUM.'期前台提现退回']);
  465. if (!$oneWithdraw->save()) {
  466. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  467. }
  468. //发票设置为审核拒绝
  469. // if ($invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw->INVOICE_ID])) {
  470. // $invoiceModel->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
  471. // $invoiceModel->AUDIT_REMARK = '提现退回';
  472. // $invoiceModel->AUDITED_AT = Date::nowTime();
  473. // if (!$invoiceModel->save()) {
  474. // throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
  475. // }
  476. // }
  477. $transaction->commit();
  478. } catch (Exception $e) {
  479. $transaction->rollBack();
  480. $this->addError('auditStatus', $e->getMessage());
  481. return null;
  482. }
  483. return $oneWithdraw;
  484. }
  485. /**
  486. * 设置提现订单的状态
  487. * @return null|static
  488. * @throws \yii\db\Exception
  489. */
  490. public function changeStatus() {
  491. if (!$this->validate()) {
  492. return null;
  493. }
  494. $logs = [];
  495. $db = \Yii::$app->db;
  496. $transaction = $db->beginTransaction();
  497. try {
  498. foreach ($this->selectedIds as $select) {
  499. $oneWithdraw = Withdraw::findOne(['ID' => $select]);
  500. //判断状态
  501. if (($msg = Withdraw::chkAuditStatus($oneWithdraw->SN, $oneWithdraw->AUDIT_STATUS, $this->auditStatus)) != '') {
  502. throw new Exception($msg);
  503. }
  504. //待审核->已审核
  505. if ($this->auditStatus == Withdraw::STATUS_AUDITED) {
  506. //同时审核发票
  507. if ($invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw['INVOICE_ID']])) {
  508. if (InvoiceAudit::find()->where('INVOICE_NUM=:INVOICE_NUM AND WITHDRAW_ID!=:WITHDRAW_ID AND AUDIT_STATUS=:AUDIT_STATUS', [':INVOICE_NUM' => $invoiceModel->INVOICE_NUM, ':WITHDRAW_ID' => $invoiceModel->WITHDRAW_ID, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['true']['value']])->exists()) {
  509. throw new Exception('提现流水号' . $oneWithdraw->SN . '发票的发票号码【' . $invoiceModel->INVOICE_NUM . '】已被使用');
  510. }
  511. $invoiceModel->AUDIT_ADMIN = \Yii::$app->user->id;
  512. $invoiceModel->CREATE_REMARK = $this->createRemark ?? '';
  513. $invoiceModel->AUDITED_AT = Date::nowTime();
  514. if (!$invoiceModel->save()) {
  515. throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
  516. }
  517. }
  518. $oneWithdraw->REMARK = $this->createRemark ?? '';
  519. } //已审核->待付款
  520. elseif ($this->auditStatus == Withdraw::STATUS_WAIT_PAID) {
  521. $oneWithdraw->PAID_FAIL_REMARK = '';
  522. $oneWithdraw->PAID_FAIL_AT = 0;
  523. $oneWithdraw->REMARK = $this->createRemark ?? '';
  524. $oneWithdraw->PLAN_PAID_AT = Date::utcToTime($this->planPaidAt);
  525. } //待付款->已付款
  526. elseif ($this->auditStatus == Withdraw::STATUS_PAID) {
  527. $oneWithdraw->PAID_AT = Date::utcToTime($this->paidAt);
  528. //记录付款信息
  529. $baseInfo = Info::baseInfo($oneWithdraw->USER_ID);
  530. if ($baseInfo['REG_TYPE'] == '758BF69C25C3422AA7743936BC77EE64') {
  531. $companyBank = CompanyBank::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseInfo['ID']]);
  532. $oneWithdraw->REAL_NAME = $companyBank['OPEN_NAME'];
  533. $oneWithdraw->OPEN_BANK = $companyBank['OPEN_BANK'];
  534. $oneWithdraw->BANK_PROVINCE = $companyBank['BANK_PROVINCE'];
  535. $oneWithdraw->BANK_CITY = $companyBank['BANK_CITY'];
  536. $oneWithdraw->BANK_COUNTY = $companyBank['BANK_COUNTY'];
  537. $oneWithdraw->BANK_ADDRESS = $companyBank['BANK_ADDRESS'];
  538. $oneWithdraw->BANK_NO = $companyBank['BANK_NO'];
  539. } else {
  540. $oneWithdraw->REAL_NAME = $baseInfo['REAL_NAME'];
  541. $oneWithdraw->OPEN_BANK = $baseInfo['OPEN_BANK'];
  542. $oneWithdraw->BANK_PROVINCE = $baseInfo['BANK_PROVINCE'];
  543. $oneWithdraw->BANK_CITY = $baseInfo['BANK_CITY'];
  544. $oneWithdraw->BANK_COUNTY = $baseInfo['BANK_COUNTY'];
  545. $oneWithdraw->BANK_ADDRESS = $baseInfo['BANK_ADDRESS'];
  546. $oneWithdraw->BANK_NO = $baseInfo['BANK_NO'];
  547. }
  548. $oneWithdraw->REMARK = $this->createRemark ?? '';
  549. } //已付款->付款失败
  550. elseif ($this->auditStatus == Withdraw::STATUS_PAID_FALSE) {
  551. $oneWithdraw->PAID_FAIL_AT = Date::nowTime();
  552. $oneWithdraw->PAID_FAIL_REMARK = $this->createRemark ?? '';
  553. } //提现退回
  554. elseif ($this->auditStatus == Withdraw::STATUS_RETURN) {
  555. $oneWithdraw->BACK_REMARK = $this->createRemark ?? '';
  556. $oneWithdraw->BACK_FAIL_AT = Date::nowTime();
  557. Balance::changeUserBonus($oneWithdraw['USER_ID'], 'BONUS', abs($oneWithdraw['AMOUNT']), ['DEAL_TYPE_ID' => DealType::WITHDRAW_RETURN, 'REMARK' => $oneWithdraw->WITHDRAW_PERIOD_NUM . '期' . ($oneWithdraw->IS_AUTO_WITHDRAW ? '自动' : '手动') . '提现退回']);
  558. //发票设置为审核拒绝
  559. $invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw->INVOICE_ID]);
  560. if ($invoiceModel) {
  561. $invoiceModel->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
  562. $invoiceModel->AUDIT_ADMIN = \Yii::$app->user->id;
  563. $invoiceModel->AUDIT_REMARK = '提现退回';
  564. $invoiceModel->AUDITED_AT = Date::nowTime();
  565. if (!$invoiceModel->save()) {
  566. throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
  567. }
  568. }
  569. }
  570. $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
  571. $oneWithdraw->AUDIT_STATUS = $this->auditStatus;
  572. $oneWithdraw->AUDITED_AT = Date::nowTime();
  573. if (!$oneWithdraw->save()) {
  574. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  575. }
  576. $logs[$select] = $oneWithdraw->SN;
  577. }
  578. $adminId = \Yii::$app->user->id;
  579. \Yii::$app->redis->del('withdrawAudit_'.$adminId);
  580. $transaction->commit();
  581. } catch (Exception $e) {
  582. $transaction->rollBack();
  583. $this->addError('auditStatus', $e->getMessage());
  584. return null;
  585. }
  586. return ['logs' => $logs, 'status' => $this->auditStatus];
  587. }
  588. /**
  589. * 标记为付款失败
  590. * @return null|static
  591. * @throws \yii\db\Exception
  592. */
  593. public function excelPaidFalse() {
  594. if (!$this->validate()) {
  595. return null;
  596. }
  597. $db = \Yii::$app->db;
  598. $transaction = $db->beginTransaction();
  599. try {
  600. $oneWithdraw = Withdraw::findOne(['SN' => $this->sn]);
  601. $oneWithdraw->PAID_FAIL_AT = Date::nowTime();
  602. $oneWithdraw->PAID_FAIL_REMARK = $this->paidFailRemark;
  603. $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
  604. $oneWithdraw->AUDIT_STATUS = Withdraw::STATUS_PAID_FALSE;
  605. $oneWithdraw->AUDITED_AT = Date::nowTime();
  606. if (!$oneWithdraw->save()) {
  607. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  608. }
  609. $transaction->commit();
  610. } catch (Exception $e) {
  611. $transaction->rollBack();
  612. $this->addError('auditStatus', $e->getMessage());
  613. return null;
  614. }
  615. return $oneWithdraw;
  616. }
  617. /**
  618. * 循环自动提现
  619. * @param $limit
  620. * @param int $start
  621. * @return bool
  622. * @throws \yii\db\Exception
  623. */
  624. public static function autoLoopWithdraw($limit, $start = 0) {
  625. // 获取设置自动提现的最低金额
  626. $systemConfig = Cache::getSystemConfig();
  627. $autoWithdrawMinAmount = $systemConfig['autoWithdrawMinAmount']['VALUE'];
  628. $autoWithdrawMaxAmount = $systemConfig['autoWithdrawMaxAmount']['VALUE'];
  629. // 获取全部设置了自动提现的会员的奖金大于这个数额的会员
  630. $allData = UserInfo::find()->select('UI.USER_ID,UI.USER_NAME,UI.IS_BIND_MAIN,UB.BONUS,UB.BONUS_FREEZE')->from(UserInfo::tableName() . ' AS UI')->join('LEFT JOIN', UserBonus::tableName() . ' AS UB', 'UI.USER_ID=UB.USER_ID')->where('UI.IS_AUTO_WITHDRAW=1 AND (UI.IS_BIND_MAIN=1 OR (UB.BONUS - UB.BONUS_FREEZE >= :WITHDRAW_AMOUNT AND UI.IS_BIND=0))', [':WITHDRAW_AMOUNT' => $autoWithdrawMinAmount])->offset($start)->limit($limit)->asArray()->all();
  631. if ($allData) {
  632. foreach ($allData as $data) {
  633. //本月提现过的忽略
  634. if (Withdraw::hasThisMonthWithdraw($data['USER_ID'])) continue;
  635. //汇总主点位
  636. $collectBind = 0;
  637. if ($data['IS_BIND_MAIN'] == 1) {
  638. $transferBonusForm = new TransferBonusForm();
  639. $collectBind = $transferBonusForm->collectBind($data['USER_ID']);
  640. }
  641. $totalAmount = $data['BONUS'] + $collectBind - $data['BONUS_FREEZE'];
  642. if ($autoWithdrawMinAmount != 0 && $totalAmount < $autoWithdrawMinAmount) continue;
  643. $formModel = new WithdrawForm();
  644. $formModel->scenario = 'addByAuto';
  645. $formModel->userName = $data['USER_NAME'];
  646. //自动提现金额取整数
  647. $formModel->applyAmount = floor(($autoWithdrawMaxAmount > 0 && $totalAmount > $autoWithdrawMaxAmount) ? $autoWithdrawMaxAmount : $totalAmount);
  648. if (!$formModel->add()) {
  649. continue;
  650. }
  651. unset($formModel);
  652. }
  653. unset($allData);
  654. $start = $start + $limit;
  655. return self::autoLoopWithdraw($limit, $start);
  656. }
  657. return true;
  658. }
  659. }