UploadForm.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Cache;
  4. use common\components\Model;
  5. use common\helpers\Date;
  6. use common\helpers\Excel;
  7. use common\helpers\Form;
  8. use common\helpers\http\RemoteUploadApi;
  9. use common\helpers\ocr\OcrApi;
  10. use common\helpers\Tool;
  11. use common\helpers\user\Info;
  12. use common\models\ExcelAddUser;
  13. use common\models\ExcelImport;
  14. use common\models\InvoiceAudit;
  15. use common\models\Recharge;
  16. use common\models\Uploads;
  17. use common\models\User;
  18. use common\models\Withdraw;
  19. use yii\base\Exception;
  20. /**
  21. * Login form
  22. */
  23. class UploadForm extends Model {
  24. public $file;
  25. public $excelOption; // 导入的excel文件用来干什么,存入excel导入表
  26. public $token;
  27. public $remark;
  28. public $withdrawId;
  29. public $rechargeId;
  30. private $_ocrResult;
  31. private $_remoteScenario = [
  32. // 'idCardFront', 'idCardBack', 'ad', 'invoiceFront','proveFront','goodsImg'
  33. ];
  34. /**
  35. * @inheritdoc
  36. */
  37. public function rules() {
  38. return [
  39. [['remark', 'withdrawId', 'rechargeId'], 'trim'],
  40. [['file', 'token', 'excelOption'], 'required'],
  41. [['token'], 'isToken'],
  42. [['file'], 'file'],
  43. [['file'], 'file', 'mimeTypes' => ['image/jpeg', 'image/png', 'image/x-png'], 'on' => ['idCardFront', 'idCardBack', 'ad']],
  44. // todo 暂时屏蔽
  45. // [['file'], 'file', 'mimeTypes'=>['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'], 'on'=>['excel']],
  46. [['file'], 'isIdCardFront', 'on' => ['idCardFront']],
  47. [['file'], 'isInvoiceFront', 'on' => ['invoiceFront']],
  48. //[['file'], 'isIdCardBack', 'on'=>['idCardBack']],
  49. ];
  50. }
  51. /**
  52. * 指定校验场景
  53. * @return array
  54. */
  55. public function scenarios() {
  56. $parentScenarios = parent::scenarios();
  57. $customScenarios = [
  58. 'idCardFront' => ['file', 'token'],
  59. 'idCardBack' => ['file', 'token'],
  60. 'invoiceFront' => ['file', 'token', 'remark', 'withdrawId'],
  61. 'proveFront' => ['file', 'token', 'rechargeId'],
  62. 'ad' => ['file', 'token'],
  63. 'article' => ['file', 'token'],
  64. 'excel' => ['file', 'token', 'excelOption'],
  65. 'goodsImg' => ['file', 'token'],
  66. ];
  67. return array_merge($parentScenarios, $customScenarios);
  68. }
  69. public function attributeLabels() {
  70. return [
  71. 'file' => '文件',
  72. ];
  73. }
  74. /**
  75. * 校验上传token
  76. * @param $attributes
  77. */
  78. public function isToken($attributes) {
  79. if (!Cache::getUploadToken($this->token)) {
  80. $this->addError($attributes, '上传token校验失败');
  81. }
  82. }
  83. /**
  84. * 是否是身份证
  85. * @param $attributes
  86. */
  87. public function isIdCardFront($attributes) {
  88. // 查看该用户是否已经上传过身份证照片
  89. $oneData = User::find()->select('ID_IMAGE')->where('ID=:ID', [':ID' => \Yii::$app->user->id])->asArray()->one();
  90. if ($oneData['ID_IMAGE']) {
  91. $this->addError($attributes, '您已上传过身份证照片');
  92. }
  93. $this->_ocrResult = OcrApi::instance()->idCard($this->file->tempName);
  94. if (!$this->_ocrResult['success']) {
  95. $this->addError($attributes, $this->_ocrResult['message']);
  96. }
  97. }
  98. /**
  99. * 前台上传发票
  100. * @param $attributes
  101. */
  102. public function isInvoiceFront($attributes) {
  103. $this->_ocrResult = OcrApi::instance()->vatInvoice($this->file->tempName);
  104. if (!$this->_ocrResult['success']) {
  105. $this->addError($attributes, $this->_ocrResult['message']);
  106. }
  107. }
  108. /**
  109. * 上传
  110. * @return bool
  111. * @throws \yii\db\Exception
  112. */
  113. public function upload() {
  114. if (!$this->validate()) {
  115. return false;
  116. }
  117. $oneUser = User::findOne(['ID' => \Yii::$app->user->id]);
  118. $db = \Yii::$app->db;
  119. $transaction = $db->beginTransaction();
  120. try {
  121. switch ($this->scenario) {
  122. case 'invoiceFront':
  123. $uploadCategory = Uploads::CATEGORY_INVOICE;
  124. $uploadRemark = $this->remark;
  125. break;
  126. case 'idCardFront':
  127. $uploadCategory = Uploads::CATEGORY_ID_CARD;
  128. $uploadRemark = $this->_ocrResult['realName'] . '身份证正面';
  129. break;
  130. case 'idCardBack':
  131. $uploadCategory = Uploads::CATEGORY_ID_CARD;
  132. $uploadRemark = $oneUser['REAL_NAME'] . '身份证背面';
  133. break;
  134. case 'proveFront':
  135. case 'goodsImg':
  136. case 'ad':
  137. $uploadCategory = Uploads::CATEGORY_IMAGE;
  138. $uploadRemark = $this->file->baseName;
  139. break;
  140. case 'excel':
  141. $uploadCategory = Uploads::CATEGORY_EXCEL;
  142. $uploadRemark = $this->file->baseName;
  143. break;
  144. default :
  145. $uploadCategory = Uploads::CATEGORY_UN_KNOW;
  146. $uploadRemark = $this->file->baseName;
  147. break;
  148. }
  149. // 上传图片到远程服务器
  150. if (in_array($this->scenario, $this->_remoteScenario)) {
  151. $remoteUploadApi = RemoteUploadApi::instance();
  152. if ($uploadResult = $remoteUploadApi->upload($this->file->tempName)) {
  153. $uploadInfo = [
  154. 'fileName' => $uploadResult['name'],
  155. 'category' => $uploadCategory,
  156. 'url' => $uploadResult['url'],
  157. 'fileSize' => $uploadResult['size'] ?? null,
  158. 'md5' => $uploadResult['md5'] ?? null,
  159. ];
  160. } else {
  161. throw new Exception('Remote service error');
  162. }
  163. // 删除本地临时文件
  164. unlink($this->file->tempName);
  165. } else {
  166. // 生成文件名
  167. $fileName = Tool::generateId(false);
  168. // 保存在本地
  169. $localPath = \Yii::getAlias('@common/runtime/uploads/') . $fileName . '.' . $this->file->extension;
  170. if (!$this->file->saveAs($localPath)) {
  171. throw new Exception('Failed');
  172. }
  173. $uploadInfo = [
  174. 'fileName' => $fileName . '.' . $this->file->extension,
  175. 'category' => $uploadCategory,
  176. // 'url' => $localPath,
  177. 'url' => $fileName . '.' . $this->file->extension,
  178. 'fileSize' => null,
  179. 'md5' => null,
  180. ];
  181. }
  182. // 把上传的文件写入数据库记录中
  183. // 把文件对应的相关资料存入数据库中
  184. $uploads = new Uploads();
  185. $uploads->FILE_NAME = $uploadInfo['fileName'];
  186. $uploads->CATEGORY = $uploadInfo['category'];
  187. $uploads->URL = $uploadInfo['url'];
  188. $uploads->FILE_SIZE = $uploadInfo['fileSize'] ?? null;
  189. $uploads->MD5 = $uploadInfo['md5'] ?? null;
  190. $uploads->REMARK = $uploadRemark;
  191. $uploads->CREATED_AT = Date::nowTime();
  192. if (!$uploads->save()) {
  193. throw new Exception('Save error');
  194. }
  195. // 如果是上传发票,更新发票信息,并绑定提现记录
  196. if ($this->scenario == 'invoiceFront') {
  197. $withdraw = Withdraw::findOne(['ID' => $this->withdrawId]);
  198. //判断金额是否一致
  199. if ($withdraw['AMOUNT'] != $this->_ocrResult['amount']) {
  200. throw new Exception('上传发票金额'.$this->_ocrResult['amount'].'与提现金额【'.$withdraw['AMOUNT'].'】不一致');
  201. }
  202. //发票内容是否与后台预置信息相符
  203. $configName = Cache::getSystemConfig()['invoiceItemName']['VALUE'];
  204. if (!in_array($this->_ocrResult['itemName'], explode("\n",$configName))) {
  205. throw new Exception('上传发票中货物或应税劳务服务名称与后台预置信息【' . $configName . '】不一致');
  206. }
  207. //写入发票数据
  208. if (InvoiceAudit::find()->where('INVOICE_NUM=:INVOICE_NUM AND WITHDRAW_ID!=:WITHDRAW_ID AND AUDIT_STATUS!=:AUDIT_STATUS', [':INVOICE_NUM' => $this->_ocrResult['invoiceNum'], ':WITHDRAW_ID' => $this->withdrawId, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['reject']['value']])->exists()) {
  209. throw new Exception('该发票已被使用');
  210. }
  211. if(!$invoiceModel = InvoiceAudit::findOne(['WITHDRAW_ID' => $this->withdrawId])){
  212. $invoiceModel = new InvoiceAudit();
  213. }
  214. $invoiceModel->USER_ID = $oneUser['ID'];
  215. $invoiceModel->WITHDRAW_ID = $this->withdrawId;
  216. $invoiceModel->INVOICE_CODE = $this->_ocrResult['invoiceCode'];
  217. $invoiceModel->INVOICE_NUM = $this->_ocrResult['invoiceNum'];
  218. $invoiceModel->INVOICE_DATE = $this->_ocrResult['invoiceDate'];
  219. $invoiceModel->AMOUNT = $this->_ocrResult['amount'];
  220. $invoiceModel->TAX_RATE = $this->_ocrResult['taxRate'];
  221. $invoiceModel->PURCHASER_NAME = $this->_ocrResult['purchaserName'];
  222. $invoiceModel->PURCHASER_REGISTER_NUM = $this->_ocrResult['purchaserRegisterNum'];
  223. $invoiceModel->PURCHASER_ADDRESS = $this->_ocrResult['purchaserAddress'];
  224. $invoiceModel->PURCHASER_BANK = $this->_ocrResult['purchaserBank'];
  225. $invoiceModel->SELLER_NAME = $this->_ocrResult['sellerName'];
  226. $invoiceModel->SELLER_REGISTER_NUM = $this->_ocrResult['sellerRegisterNum'];
  227. $invoiceModel->SELLER_ADDRESS = $this->_ocrResult['sellerAddress'];
  228. $invoiceModel->SELLER_BANK = $this->_ocrResult['sellerBank'];
  229. $invoiceModel->ITEM_NAME = $this->_ocrResult['itemName'];
  230. $invoiceModel->INVOICE_REMARK = $this->_ocrResult['invoiceRemark'];
  231. $invoiceModel->UPLOAD_ID = $uploads->ID;
  232. $invoiceModel->CREATED_AT = Date::nowTime();
  233. if (!$invoiceModel->save()) {
  234. throw new Exception(Form::formatErrorsForApi($invoiceModel->getErrors()));
  235. }
  236. //写入提现表
  237. $withdraw->INVOICE_ID = $invoiceModel->ID;
  238. $withdraw->AUDIT_STATUS = Withdraw::STATUS_APPLIED;
  239. $withdraw->UPDATED_AT = Date::nowTime();
  240. if (!$withdraw->save()) {
  241. throw new Exception(Form::formatErrorsForApi($withdraw->getErrors()));
  242. }
  243. } // 如果是上传身份证正面的场景,则把识别出来的信息更新当前的会员信息
  244. elseif ($this->scenario == 'idCardFront') {
  245. // 修改用户基本信息
  246. $oneUser->REAL_NAME = $this->_ocrResult['realName'];
  247. $oneUser->ID_CARD = $this->_ocrResult['idCardNo'];
  248. $oneUser->ADDRESS = $this->_ocrResult['address'];
  249. $oneUser->NATION = Info::getNationCode($this->_ocrResult['nation']);
  250. $oneUser->ID_IMAGE = $uploadInfo['url'];
  251. if (!$oneUser->save()) {
  252. // throw new Exception('用户基本资料保存失败');
  253. throw new Exception(Form::formatErrorsForApi($oneUser->getErrors()));
  254. }
  255. // 更新会员信息缓存
  256. User::updateBaseInfoToRedis($oneUser['ID']);
  257. } elseif ($this->scenario == 'excel') {
  258. $excelTableClass = Excel::EXCEL_STRUCTURE[$this->excelOption]['excelTableClass'];
  259. // 把上传的文件写入到导入记录中
  260. $excelImport = new ExcelImport();
  261. $excelImport->OPTION_NAME = $this->excelOption;
  262. $excelImport->TABLE_NAME = $excelTableClass::tableName();
  263. $excelImport->UPLOAD_ID = $uploads->ID;
  264. $excelImport->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
  265. $excelImport->IMPORT_ADMIN_ID = \Yii::$app->user->id;
  266. $excelImport->AUDIT_ADMIN_ID = \Yii::$app->user->id;
  267. $excelImport->CREATED_AT = Date::nowTime();
  268. if (!$excelImport->save()) {
  269. throw new Exception(Form::formatErrorsForApi($excelImport->getErrors()));
  270. }
  271. }elseif ($this->scenario == 'proveFront') {
  272. // 如果是上传充值凭证,绑定充值记录
  273. $recharge = Recharge::findOne(['ID' => $this->rechargeId]);
  274. if(!$recharge){
  275. throw new Exception("缺少参数ID");
  276. }
  277. //写入充值表
  278. $recharge->BANK_PROVE = $uploadInfo['url'];
  279. $recharge->AUDIT_STATUS = Recharge::STATUS_PROVED;
  280. if (!$recharge->save()) {
  281. throw new Exception(Form::formatErrorsForApi($recharge->getErrors()));
  282. }
  283. }
  284. $transaction->commit();
  285. } catch (Exception $e) {
  286. $transaction->rollBack();
  287. $this->addError('upload', $e->getMessage());
  288. return false;
  289. }
  290. return $uploads;
  291. }
  292. }