WithdrawForm.php 35 KB

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