WithdrawForm.php 35 KB

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