WithdrawForm.php 33 KB

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