WithdrawForm.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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' => '提现申请不存在'],
  70. [['userName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME', 'message' => '会员不存在'],
  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, '输入的会员姓名或身份证号与系统不一致');
  125. }
  126. if ($userInfo['REG_TYPE'] != $this->regType) {
  127. $this->addError($attributes, '选择的会员注册类型与系统不一致');
  128. }
  129. }
  130. $this->_userId = $userInfo['USER_ID'];
  131. } else {
  132. $this->addError($attributes, $this->userName . 'Member does not exist'); // 会员不存在
  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', '提现金额必须大于0');
  144. }
  145. if ((int)($this->applyAmount)!=$this->applyAmount) {
  146. $this->addError('scenario', '提现金额必须是整数');
  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, '场景不存在');
  159. return false;
  160. }
  161. if ($minAmount != 0 && $this->applyAmount < $minAmount) {
  162. $this->addError($attribute, '提现金额不能少于' . $minAmount . '元');
  163. }
  164. if ($maxAmount != 0 && $this->applyAmount > $maxAmount) {
  165. $this->addError($attribute, '提现金额不能高于' . $maxAmount . '元');
  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', '提现金额必须小于的可用余额');
  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, 'The payment password is incorrect');//支付密码不正确
  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, '申请提现校验失败');
  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, '提现审核校验失败');
  203. }
  204. }
  205. /**
  206. * 批量数据
  207. * @param $attributes
  208. */
  209. public function isSelected($attributes) {
  210. if (!$this->selectedIds) {
  211. $this->addError($attributes, 'A piece of data must be selected'); // 必须选择一条数据
  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, '不能选择过去的日期');
  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, '不存在提现流水号为' . $sn . '的已付款记录');
  241. }
  242. if ($oneWithdraw) {
  243. $info = Info::baseInfo($oneWithdraw['USER_ID']);
  244. if ($this->userName != $info['USER_NAME']) {
  245. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的用户名' . $this->userName . '与系统中的信息【' . $info['USER_NAME'] . '】不一致');
  246. }
  247. if ($this->realName != $info['REAL_NAME']) {
  248. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的会员姓名' . $this->realName . '与系统中的信息【' . $info['REAL_NAME'] . '】不一致');
  249. }
  250. if ($this->withdrawPeriodNum != $oneWithdraw['WITHDRAW_PERIOD_NUM']) {
  251. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的提现期数' . $this->withdrawPeriodNum . '与系统中的信息【' . $oneWithdraw['WITHDRAW_PERIOD_NUM'] . '】不一致');
  252. }
  253. if (Date::convert(Date::utcToTime($this->paidAt)) != Date::convert($oneWithdraw['PAID_AT'])) {
  254. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的付款日期' . Date::convert(Date::utcToTime($this->paidAt)) . '与系统中的信息【' . Date::convert($oneWithdraw['PAID_AT']) . '】不一致');
  255. }
  256. if ($this->amount != $oneWithdraw['AMOUNT']) {
  257. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的提现金额' . $this->amount . '与系统中的信息【' . $oneWithdraw['AMOUNT'] . '】不一致');
  258. }
  259. if ($this->bankRealName != $oneWithdraw['REAL_NAME']) {
  260. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的实时开户名' . $this->bankRealName . '与系统中的信息【' . $oneWithdraw['REAL_NAME'] . '】不一致');
  261. }
  262. if ($this->bankNo != $oneWithdraw['BANK_NO']) {
  263. $this->addError($attribute, 'Excel中提现流水号' . $sn . '的实时银行账户' . $this->bankNo . '与系统中的信息【' . $oneWithdraw['BANK_NO'] . '】不一致');
  264. }
  265. }
  266. }
  267. /**
  268. * 添加提现申请
  269. * @return null|string
  270. * @throws \yii\db\Exception
  271. */
  272. public function add() {
  273. if (!$this->validate()) {
  274. return false;
  275. }
  276. $beforeData = Balance::getLogData(\Yii::$app->user->id);
  277. $this->userOperateLogger->saveBeforeContent=$beforeData;
  278. $config = Cache::getSystemConfig();
  279. $db = \Yii::$app->db;
  280. $transaction = $db->beginTransaction();
  281. try {
  282. $nowTime = $this->createdAt ? $this->createdAt : Date::nowTime();
  283. $period = Withdraw::getPeriod($nowTime);
  284. //扣除会员奖金
  285. 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]);
  286. //增加记录
  287. $userInfo = Info::baseInfo($this->_userId);
  288. //手续费
  289. $fees = $this->applyAmount * $config['withdrawFee']['VALUE']/100;
  290. $fees = Tool::formatPrice($fees);
  291. $realAmount = $this->applyAmount - $fees;
  292. //判断付款类型
  293. $payType = Withdraw::PAY_TYPE_NO_INVOICE;
  294. $withdrawModel = new Withdraw();
  295. $withdrawModel->SN = $this->_generateSn();
  296. $withdrawModel->USER_ID = $this->_userId;
  297. $withdrawModel->ID_CARD = $userInfo['ID_CARD'];
  298. $withdrawModel->WITHDRAW_PERIOD_NUM = $period['nowPeriodNum'];
  299. $withdrawModel->WITHDRAW_YEAR = $period['nowYear'];
  300. $withdrawModel->WITHDRAW_MONTH = $period['nowMonth'];
  301. $withdrawModel->PAY_TYPE = $payType;
  302. $withdrawModel->IS_AUTO_WITHDRAW = $this->scenario == 'addByAuto' ? 1 : 0;
  303. $withdrawModel->AMOUNT = $this->applyAmount;
  304. $withdrawModel->FEES = $fees;
  305. $withdrawModel->REAL_AMOUNT = $realAmount;
  306. $withdrawModel->P_MONTH = Date::ociToDate($period['yearMonth'], Date::OCI_TIME_FORMAT_SHORT_MONTH);
  307. // if ($payType == Withdraw::PAY_TYPE_NO_INVOICE) {
  308. // $withdrawModel->AUDIT_STATUS = Withdraw::STATUS_AUDITED;
  309. // $withdrawModel->AUDITED_AT = $nowTime;
  310. // } else {
  311. $withdrawModel->AUDIT_STATUS = Withdraw::STATUS_APPLIED;
  312. // }
  313. $withdrawModel->CREATED_AT = $nowTime;
  314. //预计付款时间
  315. $withdrawModel->PLAN_PAID_AT = $period['endTime'] + $config['withdrawFreezeDays']['VALUE'] * 3600 * 24;
  316. if ($this->scenario == 'addByAdmin') {
  317. $withdrawModel->UPDATE_ADMIN = \Yii::$app->user->id;
  318. $withdrawModel->UPDATE_REMARK = $this->createRemark;
  319. }
  320. if (!$withdrawModel->save()) {
  321. throw new Exception(Form::formatErrorsForApi($withdrawModel->getErrors()));
  322. }
  323. //考核会员注册类型
  324. // RegType::chkRegType($this->_userId, $userInfo['SHOULD_REG_TYPE'], $period['nowYear'], $period['nowMonth']);
  325. $transaction->commit();
  326. } catch (Exception $e) {
  327. $transaction->rollBack();
  328. $this->addError('add', $e->getMessage());
  329. return false;
  330. }
  331. $afterData = Balance::getLogData(\Yii::$app->user->id);
  332. $this->userOperateLogger->saveAfterContent=$afterData;
  333. unset($beforeData,$afterData);
  334. $this->userOperateLogger->clean()->save([
  335. 'optType' => '会员提现申请',
  336. 'userId' => \Yii::$app->user->id,
  337. 'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
  338. 'remark' => $this->createRemark,
  339. ]);
  340. return $withdrawModel;
  341. }
  342. /**
  343. * 检测是否上传身份证
  344. * @return int
  345. */
  346. public function checkHasIdCardInfo() {
  347. if ($this->scenario !== 'addByUser') return 0;
  348. $userId = \Yii::$app->user->id;
  349. $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'ID,USER_NAME,ID_CARD');
  350. if( !$user ) {
  351. $this->addError('add', '不存在该用户');
  352. return -1;
  353. }
  354. // if( !$user['ID_CARD'] ) {
  355. // $this->addError('add', '完善身份信息后才可以提现');
  356. // return -1;
  357. // }
  358. //
  359. // $response = LingYunGongApi::hasIdCardInfo($user['ID_CARD']);
  360. // if( !$response ) {
  361. // $this->addError('add', '接口网络错误');
  362. // return -1;
  363. // }
  364. //
  365. // if( !isset($response['has']) ) {
  366. // $this->addError('add', '接口格式错误');
  367. // return -1;
  368. // }
  369. //
  370. //
  371. // if( $response['has'] === true ) {
  372. // return 0;
  373. // }else {
  374. // $this->addError('add', $response['err_msg']['msg']);
  375. // return -2;
  376. // }
  377. return 0;
  378. }
  379. /**
  380. * 生成流水号
  381. * @return string
  382. */
  383. private function _generateSn() {
  384. return 'TX' . Date::today('Ymd') . $this->_random(10, 1);
  385. }
  386. /**
  387. * 生成随机数
  388. *
  389. * @param $length
  390. * @param int $numeric
  391. * @return string
  392. */
  393. private function _random($length, $numeric = 0) {
  394. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  395. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  396. $hash = '';
  397. $max = strlen($seed) - 1;
  398. for ($i = 0; $i < $length; $i++) {
  399. $hash .= $seed[mt_rand(0, $max)];
  400. }
  401. return $hash;
  402. }
  403. /**
  404. * 生成随机数
  405. * @param $length
  406. * @param int $numeric
  407. * @return string
  408. */
  409. public function wdcode($length, $numeric = 0) {
  410. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  411. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  412. $hash = '';
  413. $max = strlen($seed) - 1;
  414. for ($i = 0; $i < $length; $i++) {
  415. $hash .= $seed[mt_rand(0, $max)];
  416. }
  417. return $hash;
  418. }
  419. /**
  420. * 修改预计打款日期
  421. * @return null|static
  422. * @throws \yii\db\Exception
  423. */
  424. public function editByAdmin() {
  425. if (!$this->validate()) {
  426. return null;
  427. }
  428. $db = \Yii::$app->db;
  429. $transaction = $db->beginTransaction();
  430. try {
  431. $oneWithdraw = Withdraw::findOne(['ID' => $this->id]);
  432. $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
  433. $oneWithdraw->REMARK = $this->createRemark;
  434. $planPaidAt = Date::utcToTime($this->planPaidAt);
  435. if ($oneWithdraw->PLAN_PAID_AT != $planPaidAt) {
  436. $oneWithdraw->PLAN_PAID_AT = $planPaidAt;
  437. }
  438. if (!$oneWithdraw->save()) {
  439. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  440. }
  441. $transaction->commit();
  442. } catch (Exception $e) {
  443. $transaction->rollBack();
  444. $this->addError('status', $e->getMessage());
  445. return null;
  446. }
  447. return $oneWithdraw;
  448. }
  449. /**
  450. * 前台提现退回
  451. * @return null|static
  452. * @throws \yii\db\Exception
  453. */
  454. public function backByUser() {
  455. if (!$this->validate()) {
  456. return null;
  457. }
  458. $oneWithdraw = Withdraw::findOne(['ID' => $this->id]);
  459. $db = \Yii::$app->db;
  460. $transaction = $db->beginTransaction();
  461. try {
  462. if (Cache::getSystemConfig()['isCanWithdrawBack']['VALUE'] != 1) {
  463. throw new Exception(Yii::t('app', 'isCanWithdrawBack'));
  464. }
  465. 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()) {
  466. throw new Exception(Yii::t('app', 'withdrawRecordDoesNotExist'));
  467. }
  468. $oneWithdraw->BACK_REMARK = $this->createRemark;
  469. $oneWithdraw->BACK_FAIL_AT = Date::nowTime();
  470. $oneWithdraw->AUDIT_STATUS = Withdraw::STATUS_RETURN;
  471. Balance::changeUserBonus($oneWithdraw['USER_ID'], 'BONUS', abs($oneWithdraw['AMOUNT']), ['DEAL_TYPE_ID'=>DealType::WITHDRAW_RETURN,'REMARK' => $oneWithdraw->WITHDRAW_PERIOD_NUM.'期前台提现退回']);
  472. if (!$oneWithdraw->save()) {
  473. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  474. }
  475. //发票设置为审核拒绝
  476. // if ($invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw->INVOICE_ID])) {
  477. // $invoiceModel->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
  478. // $invoiceModel->AUDIT_REMARK = '提现退回';
  479. // $invoiceModel->AUDITED_AT = Date::nowTime();
  480. // if (!$invoiceModel->save()) {
  481. // throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
  482. // }
  483. // }
  484. $transaction->commit();
  485. } catch (Exception $e) {
  486. $transaction->rollBack();
  487. $this->addError('auditStatus', $e->getMessage());
  488. return null;
  489. }
  490. return $oneWithdraw;
  491. }
  492. /**
  493. * 设置提现订单的状态
  494. * @return null|static
  495. * @throws \yii\db\Exception
  496. */
  497. public function changeStatus() {
  498. if (!$this->validate()) {
  499. return null;
  500. }
  501. $logs = [];
  502. $db = \Yii::$app->db;
  503. $transaction = $db->beginTransaction();
  504. try {
  505. foreach ($this->selectedIds as $select) {
  506. $oneWithdraw = Withdraw::findOne(['ID' => $select]);
  507. //判断状态
  508. if (($msg = Withdraw::chkAuditStatus($oneWithdraw->SN, $oneWithdraw->AUDIT_STATUS, $this->auditStatus)) != '') {
  509. throw new Exception($msg);
  510. }
  511. //待审核->已审核
  512. if ($this->auditStatus == Withdraw::STATUS_AUDITED) {
  513. //同时审核发票
  514. if ($invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw['INVOICE_ID']])) {
  515. 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()) {
  516. throw new Exception('提现流水号' . $oneWithdraw->SN . '发票的发票号码【' . $invoiceModel->INVOICE_NUM . '】已被使用');
  517. }
  518. $invoiceModel->AUDIT_ADMIN = \Yii::$app->user->id;
  519. $invoiceModel->CREATE_REMARK = $this->createRemark ?? '';
  520. $invoiceModel->AUDITED_AT = Date::nowTime();
  521. if (!$invoiceModel->save()) {
  522. throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
  523. }
  524. }
  525. $oneWithdraw->REMARK = $this->createRemark ?? '';
  526. } //已审核->待付款
  527. elseif ($this->auditStatus == Withdraw::STATUS_WAIT_PAID) {
  528. $oneWithdraw->PAID_FAIL_REMARK = '';
  529. $oneWithdraw->PAID_FAIL_AT = 0;
  530. $oneWithdraw->REMARK = $this->createRemark ?? '';
  531. $oneWithdraw->PLAN_PAID_AT = Date::utcToTime($this->planPaidAt);
  532. } //待付款->已付款
  533. elseif ($this->auditStatus == Withdraw::STATUS_PAID) {
  534. $oneWithdraw->PAID_AT = Date::utcToTime($this->paidAt);
  535. //记录付款信息
  536. $baseInfo = Info::baseInfo($oneWithdraw->USER_ID);
  537. if ($baseInfo['REG_TYPE'] == '758BF69C25C3422AA7743936BC77EE64') {
  538. $companyBank = CompanyBank::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseInfo['ID']]);
  539. $oneWithdraw->REAL_NAME = $companyBank['OPEN_NAME'];
  540. $oneWithdraw->OPEN_BANK = $companyBank['OPEN_BANK'];
  541. $oneWithdraw->BANK_PROVINCE = $companyBank['BANK_PROVINCE'];
  542. $oneWithdraw->BANK_CITY = $companyBank['BANK_CITY'];
  543. $oneWithdraw->BANK_COUNTY = $companyBank['BANK_COUNTY'];
  544. $oneWithdraw->BANK_ADDRESS = $companyBank['BANK_ADDRESS'];
  545. $oneWithdraw->BANK_NO = $companyBank['BANK_NO'];
  546. } else {
  547. $oneWithdraw->REAL_NAME = $baseInfo['REAL_NAME'];
  548. $oneWithdraw->OPEN_BANK = $baseInfo['OPEN_BANK'];
  549. $oneWithdraw->BANK_PROVINCE = $baseInfo['BANK_PROVINCE'];
  550. $oneWithdraw->BANK_CITY = $baseInfo['BANK_CITY'];
  551. $oneWithdraw->BANK_COUNTY = $baseInfo['BANK_COUNTY'];
  552. $oneWithdraw->BANK_ADDRESS = $baseInfo['BANK_ADDRESS'];
  553. $oneWithdraw->BANK_NO = $baseInfo['BANK_NO'];
  554. }
  555. $oneWithdraw->REMARK = $this->createRemark ?? '';
  556. } //已付款->付款失败
  557. elseif ($this->auditStatus == Withdraw::STATUS_PAID_FALSE) {
  558. $oneWithdraw->PAID_FAIL_AT = Date::nowTime();
  559. $oneWithdraw->PAID_FAIL_REMARK = $this->createRemark ?? '';
  560. } //提现退回
  561. elseif ($this->auditStatus == Withdraw::STATUS_RETURN) {
  562. $oneWithdraw->BACK_REMARK = $this->createRemark ?? '';
  563. $oneWithdraw->BACK_FAIL_AT = Date::nowTime();
  564. Balance::changeUserBonus($oneWithdraw['USER_ID'], 'BONUS', abs($oneWithdraw['AMOUNT']), [
  565. 'DEAL_TYPE_ID' => DealType::WITHDRAW_RETURN,
  566. 'REMARK' => 'Period' . $oneWithdraw->WITHDRAW_PERIOD_NUM . ' ' . ($oneWithdraw->IS_AUTO_WITHDRAW ? 'Auto' : 'Manual') . ' withdrawal return' // 自动、手动、提现退回
  567. ]);
  568. //发票设置为审核拒绝
  569. $invoiceModel = InvoiceAudit::findOne(['ID' => $oneWithdraw->INVOICE_ID]);
  570. if ($invoiceModel) {
  571. $invoiceModel->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
  572. $invoiceModel->AUDIT_ADMIN = \Yii::$app->user->id;
  573. $invoiceModel->AUDIT_REMARK = ' withdrawal return'; // 提现退回
  574. $invoiceModel->AUDITED_AT = Date::nowTime();
  575. if (!$invoiceModel->save()) {
  576. throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
  577. }
  578. }
  579. }
  580. $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
  581. $oneWithdraw->AUDIT_STATUS = $this->auditStatus;
  582. $oneWithdraw->AUDITED_AT = Date::nowTime();
  583. if (!$oneWithdraw->save()) {
  584. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  585. }
  586. $logs[$select] = $oneWithdraw->SN;
  587. }
  588. $adminId = \Yii::$app->user->id;
  589. \Yii::$app->redis->del('withdrawAudit_'.$adminId);
  590. $transaction->commit();
  591. } catch (Exception $e) {
  592. $transaction->rollBack();
  593. $this->addError('auditStatus', $e->getMessage());
  594. return null;
  595. }
  596. return ['logs' => $logs, 'status' => $this->auditStatus];
  597. }
  598. /**
  599. * 标记为付款失败
  600. * @return null|static
  601. * @throws \yii\db\Exception
  602. */
  603. public function excelPaidFalse() {
  604. if (!$this->validate()) {
  605. return null;
  606. }
  607. $db = \Yii::$app->db;
  608. $transaction = $db->beginTransaction();
  609. try {
  610. $oneWithdraw = Withdraw::findOne(['SN' => $this->sn]);
  611. $oneWithdraw->PAID_FAIL_AT = Date::nowTime();
  612. $oneWithdraw->PAID_FAIL_REMARK = $this->paidFailRemark;
  613. $oneWithdraw->UPDATE_ADMIN = \Yii::$app->user->id;
  614. $oneWithdraw->AUDIT_STATUS = Withdraw::STATUS_PAID_FALSE;
  615. $oneWithdraw->AUDITED_AT = Date::nowTime();
  616. if (!$oneWithdraw->save()) {
  617. throw new Exception(Form::formatErrorsForApi($oneWithdraw->getErrors()));
  618. }
  619. $transaction->commit();
  620. } catch (Exception $e) {
  621. $transaction->rollBack();
  622. $this->addError('auditStatus', $e->getMessage());
  623. return null;
  624. }
  625. return $oneWithdraw;
  626. }
  627. /**
  628. * 循环自动提现
  629. * @param $limit
  630. * @param int $start
  631. * @return bool
  632. * @throws \yii\db\Exception
  633. */
  634. public static function autoLoopWithdraw($limit, $start = 0) {
  635. // 获取设置自动提现的最低金额
  636. $systemConfig = Cache::getSystemConfig();
  637. $autoWithdrawMinAmount = $systemConfig['autoWithdrawMinAmount']['VALUE'];
  638. $autoWithdrawMaxAmount = $systemConfig['autoWithdrawMaxAmount']['VALUE'];
  639. // 获取全部设置了自动提现的会员的奖金大于这个数额的会员
  640. $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();
  641. if ($allData) {
  642. foreach ($allData as $data) {
  643. //本月提现过的忽略
  644. if (Withdraw::hasThisMonthWithdraw($data['USER_ID'])) continue;
  645. //汇总主点位
  646. $collectBind = 0;
  647. if ($data['IS_BIND_MAIN'] == 1) {
  648. $transferBonusForm = new TransferBonusForm();
  649. $collectBind = $transferBonusForm->collectBind($data['USER_ID']);
  650. }
  651. $totalAmount = $data['BONUS'] + $collectBind - $data['BONUS_FREEZE'];
  652. if ($autoWithdrawMinAmount != 0 && $totalAmount < $autoWithdrawMinAmount) continue;
  653. $formModel = new WithdrawForm();
  654. $formModel->scenario = 'addByAuto';
  655. $formModel->userName = $data['USER_NAME'];
  656. //自动提现金额取整数
  657. $formModel->applyAmount = floor(($autoWithdrawMaxAmount > 0 && $totalAmount > $autoWithdrawMaxAmount) ? $autoWithdrawMaxAmount : $totalAmount);
  658. if (!$formModel->add()) {
  659. continue;
  660. }
  661. unset($formModel);
  662. }
  663. unset($allData);
  664. $start = $start + $limit;
  665. return self::autoLoopWithdraw($limit, $start);
  666. }
  667. return true;
  668. }
  669. /**
  670. * 批量自动提现
  671. *
  672. *
  673. * @throws \yii\db\Exception
  674. */
  675. public function batchWithdraw($limit, $start){
  676. $config = Cache::getSystemConfig();
  677. $minAmount = $config['manualWithdrawMinAmount']['VALUE'];
  678. // 查找有奖金的用户
  679. $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();
  680. if($allData){
  681. foreach ($allData as $data){
  682. $db = \Yii::$app->db;
  683. $transaction = $db->beginTransaction();
  684. try {
  685. $nowTime = $this->createdAt ?: Date::nowTime();
  686. $period = Withdraw::getPeriod($nowTime);
  687. //扣除会员奖金
  688. Balance::changeUserBonus($data['USER_ID'], 'BONUS', -abs($data['BONUS']), ['DEAL_TYPE_ID'=>DealType::WITHDRAW,'REMARK' => 'batch withdrawal', 'TIME' => $nowTime]);
  689. //手续费
  690. $fees = $data['BONUS'] * $config['withdrawFee']['VALUE']/100;
  691. $fees = Tool::formatPrice($fees);
  692. $realAmount = $data['BONUS'] - $fees;
  693. //判断付款类型
  694. $payType = Withdraw::PAY_TYPE_NO_INVOICE;
  695. $withdrawModel = new Withdraw();
  696. $withdrawModel->SN = $this->_generateSn();
  697. $withdrawModel->USER_ID = $data['USER_ID'];
  698. $withdrawModel->ID_CARD = $data['ID_CARD'];
  699. $withdrawModel->WITHDRAW_PERIOD_NUM = $period['nowPeriodNum'];
  700. $withdrawModel->WITHDRAW_YEAR = $period['nowYear'];
  701. $withdrawModel->WITHDRAW_MONTH = $period['nowMonth'];
  702. $withdrawModel->PAY_TYPE = $payType;
  703. $withdrawModel->IS_AUTO_WITHDRAW = $this->scenario == 'batchWithdraw' ? 1 : 0;
  704. $withdrawModel->AMOUNT = $data['BONUS'];
  705. $withdrawModel->FEES = $fees;
  706. $withdrawModel->REAL_AMOUNT = $realAmount;
  707. $withdrawModel->P_MONTH = Date::ociToDate($period['yearMonth'], Date::OCI_TIME_FORMAT_SHORT_MONTH);
  708. $withdrawModel->AUDIT_STATUS = Withdraw::STATUS_APPLIED;
  709. $withdrawModel->CREATED_AT = $nowTime;
  710. //预计付款时间
  711. $withdrawModel->PLAN_PAID_AT = $period['endTime'] + $config['withdrawFreezeDays']['VALUE'] * 3600 * 24;
  712. if (!$withdrawModel->save()) {
  713. throw new Exception(Form::formatErrorsForApi($withdrawModel->getErrors()));
  714. }
  715. // print_r($data['BONUS'].',,'.$i.PHP_EOL);
  716. $transaction->commit();
  717. unset($withdrawModel);
  718. } catch (Exception $e) {
  719. $transaction->rollBack();
  720. $this->addError('add', $e->getMessage());
  721. return false;
  722. }
  723. }
  724. unset($allData);
  725. $start = $start + $limit;
  726. return self::batchWithdraw($limit, $start);
  727. }
  728. return true;
  729. }
  730. }