UploadForm.php 14 KB

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