WithdrawForm.php 34 KB

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