BaseExport.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. <?php
  2. namespace common\libs\export;
  3. use common\helpers\Cache as CacheHelper;
  4. use common\helpers\Date;
  5. use common\helpers\Form;
  6. use common\helpers\http\RemoteUploadApi;
  7. use common\helpers\Tool;
  8. use common\libs\dataList\DataList;
  9. use common\models\ApproachOrder;
  10. use common\models\ApproachOrderGoods;
  11. use common\models\Export;
  12. use common\models\Order;
  13. use common\models\OrderGoods;
  14. use common\models\Region;
  15. use common\models\ShopGoods;
  16. use common\models\User;
  17. use Yii;
  18. use yii\base\Exception;
  19. use yii\base\StaticInstanceTrait;
  20. use yii\base\Component;
  21. use yii\data\Pagination;
  22. use yii\db\Query;
  23. class BaseExport extends Component {
  24. use StaticInstanceTrait;
  25. public $moduleId;
  26. /**
  27. * @var string the model class name. This property must be set.
  28. */
  29. public $modelClass;
  30. /**
  31. * @var
  32. */
  33. public $listModelClass;
  34. /**
  35. * @var int
  36. */
  37. public $pageSize = 100;
  38. /**
  39. * @var int
  40. */
  41. public $totalCount = 0;
  42. /**
  43. * @var int
  44. */
  45. public $offset = 0;
  46. /**
  47. * @var int
  48. */
  49. public $limit = 100;
  50. /**
  51. * csv文件名称
  52. * @var null
  53. */
  54. public $fileName = null;
  55. /**
  56. * 保存的基本路径
  57. * @var null
  58. */
  59. public $saveBasePath = null;
  60. /**
  61. * 保存路径
  62. * @var null
  63. */
  64. public $savePath = null;
  65. /**
  66. * 正在导出的id
  67. * 来源于exporting_file表
  68. * @var null
  69. */
  70. public $exportId = null;
  71. /**
  72. * 操作人的id
  73. * @var null
  74. */
  75. public $userId = null;
  76. /**
  77. * 任务id
  78. * @var null
  79. */
  80. public $taskId = null;
  81. /**
  82. * 是否完成
  83. * @var bool
  84. */
  85. public $completed = false;
  86. /**
  87. * @var array
  88. */
  89. public $params = [];
  90. /**
  91. * 文件句柄
  92. * @var null
  93. */
  94. private $_fp = null;
  95. /**
  96. * 是否上传远程
  97. * @var bool
  98. */
  99. public $isRemote = true;
  100. /**
  101. * @var DataList
  102. */
  103. private $_listModel;
  104. public static function factory($taskId) {
  105. return new self([
  106. 'taskId' => $taskId
  107. ]
  108. );
  109. }
  110. /**
  111. *
  112. */
  113. public function init() {
  114. parent::init();
  115. $this->isRemote = \Yii::$app->params['isRemoteUpload'];
  116. }
  117. /**
  118. * 生成复杂的路径
  119. * @return string
  120. */
  121. public function pathCreator(...$params) {
  122. $hash = md5(implode('_', $params));
  123. $first = substr($hash, 0, 3);
  124. $second = substr($hash, 3, 2);
  125. $dir = $first . __DS__ . $second . __DS__;
  126. return $dir;
  127. }
  128. /**
  129. * 获取文件名
  130. * @return string|null
  131. * @throws \Exception
  132. */
  133. public function getFileName($ext = '.csv') {
  134. $this->fileName = date('YmdHis', Date::nowTime()) . random_int(1000, 9999) . $ext;
  135. return $this->fileName;
  136. }
  137. /**
  138. * 获取保存的路径
  139. * @return array|null
  140. */
  141. public function getSavePath() {
  142. $this->savePath = $this->pathCreator(date('Ymd', Date::nowTime()));
  143. return trim($this->savePath, __DS__);
  144. }
  145. /**
  146. * @return bool|string|null
  147. */
  148. public function getSaveBasePath() {
  149. $this->saveBasePath = Yii::getAlias('@backendApi') . __DS__ . 'web' . __DS__ . 'upload' . __DS__ . \Yii::$app->params['excelLocalDir'];
  150. return trim($this->saveBasePath, __DS__);
  151. }
  152. /**
  153. * 创建目录(递归创建)
  154. *
  155. * @param $dir
  156. * @return string|false
  157. */
  158. public function mkdir($dir) {
  159. if (!is_dir($dir)) {
  160. $this->mkdir(dirname($dir));
  161. if (!mkdir($dir, 0777))
  162. return false;
  163. @exec('chown -R www:www /'.$dir);
  164. @exec('chmod -R 777 /'.$dir);
  165. }
  166. return $dir;
  167. }
  168. /**
  169. * @return array|mixed
  170. */
  171. public function getParams() {
  172. $this->params = CacheHelper::getAsyncParams($this->taskId);
  173. return $this->params;
  174. }
  175. /**
  176. * @return mixed|null
  177. */
  178. public function getUserId() {
  179. $this->userId = isset($this->params['userId']) ? $this->params['userId'] : null;
  180. return $this->userId;
  181. }
  182. /**
  183. * @return |null
  184. */
  185. public function getExportId() {
  186. $this->exportId = isset($this->params['exportId']) ? $this->params['exportId'] : null;
  187. return $this->userId;
  188. }
  189. /**
  190. * 生成
  191. * @return bool
  192. * @throws Exception
  193. * @throws \yii\base\InvalidConfigException
  194. * @throws \yii\httpclient\Exception
  195. */
  196. public function generate() {
  197. //Logger::info(date('Y-m-d H:i:s'), 'export');
  198. $this->getParams();
  199. if (!$this->params) {
  200. throw new Exception('无法获取需要的参数');
  201. }
  202. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  203. $path = __DS__ . $path;
  204. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  205. $this->completed = false;
  206. $this->getExportId();
  207. $this->getUserId();
  208. $fileNameUpdated = false;
  209. $this->_fp = fopen($realFile, 'w');
  210. @exec('chown -R www:www /'.$realFile);
  211. @exec('chmod -R 777 /'.$realFile);
  212. // 获取列表数据及表头
  213. $this->_listModel = new $this->listModelClass();
  214. $this->_listModel->isExport = true;
  215. if(method_exists($this->_listModel, 'getExportHeaders')){
  216. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  217. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => isset($this->params['others']) ? $this->params['others'] : [], 'page' => 0, 'pageSize' => $this->pageSize, 'userId' => $this->userId]);
  218. }
  219. $headers = $this->_listModel->getExportHeaders($this->userId);
  220. fputcsv($this->_fp, $headers);
  221. unset($headers);
  222. $this->_updateFirst($realFile, 1);
  223. } else {
  224. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  225. }
  226. $this->_loopWriteData($realFile, $fileNameUpdated);
  227. $this->complete();
  228. return true;
  229. }
  230. /**
  231. * 循环写入数据
  232. * @param $realFile
  233. * @param $fileNameUpdated
  234. * @param int $page
  235. * @param int $counter
  236. * @return string
  237. * @throws Exception
  238. */
  239. private function _loopWriteData($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  240. if(method_exists($this->_listModel, 'getList')){
  241. $list = $this->_listModel->getList(['condition'=>$this->params['condition'], 'params'=>isset($this->params['params']) ? $this->params['params'] : [], 'others'=>isset($this->params['others']) ? $this->params['others'] : [], 'page'=>$page, 'pageSize'=>$this->pageSize, 'userId'=>$this->userId]);
  242. } else {
  243. throw new Exception($this->listModelClass.'的getList方法不存在');
  244. }
  245. if($page >= $list['totalPages']){
  246. return 'finish';
  247. }
  248. if(!empty($list['list'])){
  249. foreach($list['list'] as $columnData){
  250. fputcsv($this->_fp, Tool::arrTextConvert($columnData));
  251. $counter++;
  252. if ($list['totalCount'] < $counter) {
  253. // $counter = $list['totalCount'];
  254. return 'finish';
  255. }
  256. $percent = intval(($counter / $list['totalCount']) * 100);
  257. $this->_updatePercent($percent);
  258. // if (!$fileNameUpdated) {
  259. // $this->_updateFirst($realFile, $percent);
  260. // } else {
  261. // $this->_updatePercent($percent);
  262. // }
  263. // $fileNameUpdated = true;
  264. unset($percent, $columnData);
  265. }
  266. $page++;
  267. unset($list);
  268. return $this->_loopWriteData($realFile, $fileNameUpdated, $page, $counter);
  269. }
  270. unset($list);
  271. return 'finish';
  272. }
  273. /**
  274. * 循环写入数据
  275. * @param $realFile
  276. * @param $fileNameUpdated
  277. * @param int $page
  278. * @param int $counter
  279. * @return string
  280. * @throws Exception
  281. */
  282. private function _loopWriteDataOrder()
  283. {
  284. LoggerTool::info($this->params);
  285. $orderQuery = Order::find()
  286. ->alias('O')
  287. ->where($this->params['condition'], $this->params['params'])
  288. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  289. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  290. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  291. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  292. ->orderBy('O.CREATED_AT DESC');
  293. // 订单中间表只查询待支付和支付失败的订单
  294. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  295. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  296. $orderStandardQuery = ApproachOrder::find()
  297. ->alias('O')
  298. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  299. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  300. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  301. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  302. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  303. ->orderBy('O.CREATED_AT DESC');
  304. $queryAll = $orderQuery->union($orderStandardQuery, true);
  305. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  306. $lists = $query->all();
  307. if(!empty($lists)){
  308. foreach($lists as $columnData){
  309. fputcsv($this->_fp, Tool::arrTextConvert($columnData));
  310. unset($percent, $columnData);
  311. }
  312. unset($list);
  313. }
  314. unset($list);
  315. return 'finish';
  316. }
  317. /**
  318. * 完成
  319. * @return bool
  320. * @throws Exception
  321. * @throws \yii\base\InvalidConfigException
  322. * @throws \yii\httpclient\Exception
  323. */
  324. public function complete() {
  325. $this->_updatePercent(100);
  326. if ($this->completed) {
  327. return true;
  328. }
  329. if ($this->_fp) {
  330. fclose($this->_fp);
  331. }
  332. // 把导出的文件上传至静态文件服务器
  333. if ($this->isRemote) {
  334. $realFile = $this->getSaveBasePath() . __DS__ . $this->getSavePath() . __DS__ . $this->getFileName();
  335. $remoteUploadApi = RemoteUploadApi::instance();
  336. if ($uploadResult = $remoteUploadApi->upload($realFile)) {
  337. Export::updateAll(['REMOTE_URL' => $uploadResult['url'], 'IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  338. } else {
  339. $this->_errorHandle();
  340. throw new Exception('文件远程上传失败');
  341. }
  342. // 删除本地临时文件
  343. unlink($realFile);
  344. } else {
  345. Export::updateAll(['IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  346. }
  347. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin(100, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  348. CacheHelper::deleteAsyncParams($this->taskId);
  349. $this->completed = true;
  350. }
  351. /**
  352. * @param $message
  353. */
  354. private function _errorNotice($message) {
  355. Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($this->userId, $message, false);
  356. }
  357. /**
  358. * 首次更新
  359. * @param $exportId
  360. * @param $realName
  361. */
  362. private function _updateFirst($realName, $percent) {
  363. $fileName = str_replace($this->getSaveBasePath() . __DS__, '', $realName);
  364. Export::updateAll([
  365. 'FILE_NAME' => str_replace(__DS__, '/', $fileName),
  366. 'UPDATED_AT' => Date::nowTime(),
  367. 'EXPORT_PERCENT' => $percent,
  368. ], 'ID=:ID', [':ID' => $this->exportId]);
  369. }
  370. /**
  371. * 更新百分比
  372. * @param $exportId
  373. * @param $percent
  374. */
  375. private function _updatePercent($percent) {
  376. // 把数据写入数据库中
  377. Export::updateAll(['EXPORT_PERCENT' => $percent], 'ID=:ID', [':ID' => $this->exportId]);
  378. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  379. }
  380. /**
  381. * 发生错误处理
  382. * @param $exportId
  383. */
  384. private function _errorHandle() {
  385. Export::updateAll(['IS_EXPORTING' => 0], 'ID=:ID', [':ID' => $this->exportId]);
  386. }
  387. /**
  388. * 导出逻辑
  389. * @param $filter
  390. * @param $listName
  391. * @param null $consoleRouter
  392. * @throws Exception
  393. */
  394. public function exportHandle($filter, $listName, $consoleRouter = null){
  395. $params = [
  396. 'moduleId' => $this->moduleId,
  397. 'listName' => $listName,
  398. 'action' => $consoleRouter ? $consoleRouter : Yii::$app->controller->id.'/'.Yii::$app->controller->action->id, // 这里这么写,是因为调用的异步路由和同步的控制器和方法是一样的,所以,只要不传默认调和同步一样的异步方法
  399. 'userId' => Yii::$app->user->id,
  400. ];
  401. $this->webToAsync($params,$filter);
  402. }
  403. /**
  404. * 页面到异步的请求
  405. * @param $params
  406. * @param array $extend
  407. * @return bool
  408. * @throws Exception
  409. */
  410. public function webToAsync($params, $extend = []) {
  411. $default = [
  412. 'moduleId' => null,
  413. 'listName' => null,
  414. 'remark' => null,
  415. 'action' => null,
  416. 'userId' => null,
  417. ];
  418. $params = Tool::deepParse($params, $default);
  419. if (!$params['moduleId'] || !$params['listName'] || !$params['action']) {
  420. throw new Exception('请设置moduleId,listName和action');
  421. }
  422. // 把文件对应的相关资料存入数据库中
  423. $export = new Export();
  424. $export->EXPORT_NAME = $params['listName'] . '_' . date('y年m月d日H时i分s秒导出', Date::nowTime());
  425. $export->MODULE_NAME = $params['moduleId'];
  426. $export->REMARK = $params['remark'];
  427. $export->IS_EXPORTING = 1;
  428. $export->ADMIN_ID = \Yii::$app->user->id;
  429. $export->STARTED_AT = Date::nowTime();
  430. $export->CREATED_AT = Date::nowTime();
  431. $export->EXPORT_PERCENT = 0;
  432. $export->ENDED_AT = 0;
  433. $export->UPDATED_AT = 0;
  434. if (!$export->save()) {
  435. throw new Exception(Form::formatErrorsForApi($export->getErrors()));
  436. }
  437. $extend = array_merge($extend, [
  438. 'exportId' => $export->ID,
  439. 'userId' => $params['userId'],
  440. ]);
  441. // 异步处理添加任务
  442. $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle($params['action'], $extend);
  443. if($taskKey === false){
  444. // 删除刚刚添加的导出数据
  445. Export::deleteAll(['ID'=>$export->ID]);
  446. throw new Exception('导出失败,请求异步处理服务器失败');
  447. }
  448. return $taskKey;
  449. }
  450. /**
  451. * 生成
  452. * @return bool
  453. * @throws Exception
  454. * @throws \yii\base\InvalidConfigException
  455. * @throws \yii\httpclient\Exception
  456. */
  457. public function generateOrderExcel() {
  458. $this->getParams();
  459. if (!$this->params) {
  460. throw new Exception('无法获取需要的参数');
  461. }
  462. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  463. $path = __DS__ . $path;
  464. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  465. $this->completed = false;
  466. $this->getExportId();
  467. $this->getUserId();
  468. $fileNameUpdated = false;
  469. $this->_fp = fopen($realFile, 'w');
  470. @exec('chown -R www:www /'.$realFile);
  471. @exec('chmod -R 777 /'.$realFile);
  472. // 获取列表数据及表头
  473. $this->_listModel = new $this->listModelClass();
  474. $this->_listModel->isExport = true;
  475. if(method_exists($this->_listModel, 'getExportHeaders')){
  476. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  477. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => isset($this->params['others']) ? $this->params['others'] : [], 'page' => 0, 'pageSize' => $this->pageSize, 'userId' => $this->userId]);
  478. }
  479. $headers = $this->_listModel->getExportHeaders($this->userId);
  480. fputcsv($this->_fp, $headers);
  481. unset($headers);
  482. $this->_updateFirst($realFile, 1);
  483. } else {
  484. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  485. }
  486. $this->_loopWriteDataOrder();
  487. $this->complete();
  488. return true;
  489. }
  490. /**
  491. * 生成
  492. * @return bool
  493. * @throws Exception
  494. * @throws \yii\base\InvalidConfigException
  495. * @throws \yii\httpclient\Exception
  496. */
  497. public function generateOrderPDF() {
  498. $this->getParams();
  499. if (!$this->params) {
  500. throw new Exception('无法获取需要的参数');
  501. }
  502. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  503. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  504. $this->completed = false;
  505. $this->getExportId();
  506. $this->getUserId();
  507. $fileNameUpdated = false;
  508. // 获取列表数据及表头
  509. $this->_listModel = new $this->listModelClass();
  510. $this->_listModel->isExport = true;
  511. // 查询订单数据
  512. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  513. $orderQuery = Order::find()
  514. ->alias('O')
  515. ->where($this->params['condition'], $this->params['params'])
  516. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  517. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  518. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  519. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  520. ->orderBy('O.CREATED_AT DESC');
  521. // 订单中间表只查询待支付和支付失败的订单
  522. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  523. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  524. $orderStandardQuery = ApproachOrder::find()
  525. ->alias('O')
  526. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  527. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  528. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  529. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  530. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  531. ->orderBy('O.CREATED_AT DESC');
  532. $queryAll = $orderQuery->union($orderStandardQuery, true);
  533. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  534. $oderList = $query->all();
  535. if ($oderList) {
  536. $userId = '';
  537. $userName = '';
  538. $address = '';
  539. $mobile = '';
  540. $orderAt = '';
  541. $orderDetails = '';
  542. $orderSn = '';
  543. $orderAmount = 0; // 合计总额
  544. $orderNums = 0; // 合计总数
  545. $totalTaxAmount = 0; // 合计税额
  546. $totalAmount = 0;
  547. foreach ($oderList as $key => $value) {
  548. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  549. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  550. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  551. $userId = $value['USER_NAME'];
  552. $userName = $value['REAL_NAME'];
  553. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  554. $mobile = $value['MOBILE'];
  555. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  556. $orderSn = $value['SN'];
  557. // 总价
  558. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  559. $orderAmount += $totalAmount;
  560. $orderNums += $value['BUY_NUMS'];
  561. // 税额
  562. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  563. $totalTaxAmount += $taxAmount;
  564. $taxAmount = Tool::formatAmount($taxAmount);
  565. $totalAmount = Tool::formatAmount($totalAmount);
  566. // 订单详情
  567. $orderDetails .= <<<EOT
  568. <tr>
  569. <td>{$value['SKU_CODE']}</td>
  570. <td>{$value['GOODS_TITLE']}</td>
  571. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  572. <td>{$value['BUY_NUMS']}</td>
  573. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  574. <td style="text-align: right;">{$taxAmount}</td>
  575. <td style="text-align: right;">{$totalAmount}</td>
  576. </tr>
  577. EOT;
  578. }
  579. // 订单基本信息
  580. $orderBase = <<<ORDER
  581. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  582. <tr>
  583. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member code</td>
  584. <td width="70%">{$userId}</td>
  585. </tr>
  586. <tr>
  587. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member name</td>
  588. <td width="70%">{$userName}</td>
  589. </tr>
  590. <tr>
  591. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member address</td>
  592. <td width="70%">{$address}</td>
  593. </tr>
  594. <tr>
  595. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member phone</td>
  596. <td width="70%">{$mobile}</td>
  597. </tr>
  598. <tr>
  599. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order code</td>
  600. <td width="70%">{$orderSn}</td>
  601. </tr>
  602. <tr>
  603. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation time</td>
  604. <td width="70%">{$orderAt}</td>
  605. </tr>
  606. <tr>
  607. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order detail</td>
  608. <td class="bg"></td>
  609. </tr>
  610. </table>
  611. ORDER;
  612. $l['a_meta_charset'] = 'UTF-8';
  613. $l['a_meta_dir'] = 'ltr';
  614. $l['a_meta_language'] = 'zh';
  615. $l['w_page'] = '页面';
  616. $orderAmount = Tool::formatAmount($orderAmount);
  617. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  618. $context = <<<ORDER
  619. <!doctype html>
  620. <html lang="en">
  621. <head>
  622. <meta charset="UTF-8" />
  623. <title>Order detail</title>
  624. <style>
  625. table {
  626. border-collapse: collapse;
  627. }
  628. table td, table th {
  629. border: 1px solid #ccc;
  630. padding: 5px 5px;
  631. border-collapse: collapse;
  632. }
  633. /*td {*/
  634. /* padding: 120px;*/
  635. /*}*/
  636. .bg {
  637. background-color: #ccc;
  638. }
  639. </style>
  640. </head>
  641. <body>
  642. <div class="content">
  643. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  644. <div>
  645. <div style="display: block; width: 100%;">
  646. {$orderBase}
  647. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  648. <tr>
  649. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product code</th>
  650. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product name</th>
  651. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product price</th>
  652. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  653. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax rate</th>
  654. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  655. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total amount</th>
  656. </tr>
  657. {$orderDetails}
  658. <tr>
  659. <td colspan="3">Total</td>
  660. <td>{$orderNums}</td>
  661. <td></td>
  662. <td style="text-align: right;">{$totalTaxAmount}</td>
  663. <td style="text-align: right;">{$orderAmount}</td>
  664. </tr>
  665. </table>
  666. </div>
  667. <div style="width: 100%; margin-top: 50px; height: 30px;">
  668. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  669. <tr style="border: none;">
  670. <td width="70%" style="border: none;"></td>
  671. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  672. </tr>
  673. <tr style="border: none;">
  674. <td width="70%" style="border: none;"></td>
  675. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  676. </tr>
  677. </table>
  678. </div>
  679. </div>
  680. </div>
  681. </body>
  682. </html>
  683. ORDER;
  684. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  685. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  686. // 设置打印模式
  687. $pdf->SetCreator(PDF_CREATOR);
  688. $pdf->SetAuthor('DaZe');
  689. $pdf->SetTitle($orderSn);
  690. $pdf->SetSubject('TCPDF Tutorial');
  691. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  692. // 是否显示页眉
  693. $pdf->setPrintHeader(false);
  694. // 设置页眉字体
  695. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  696. // 页眉距离顶部的距离
  697. $pdf->SetHeaderMargin('5');
  698. // 是否显示页脚
  699. $pdf->setPrintFooter(false);
  700. // 设置默认等宽字体
  701. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  702. // 设置行高
  703. $pdf->setCellHeightRatio(1);
  704. // 设置左、上、右的间距
  705. $pdf->SetMargins('10', '10', '10');
  706. // 设置是否自动分页 距离底部多少距离时分页
  707. $pdf->SetAutoPageBreak(TRUE, '15');
  708. // 设置图像比例因子
  709. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  710. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  711. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  712. $pdf->setLanguageArray($l);
  713. }
  714. $pdf->setFontSubsetting(true);
  715. $pdf->AddPage();
  716. // 设置字体
  717. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  718. $pdf->writeHTML($context);
  719. $pdf->Output($realFile, 'F');
  720. $this->_updateFirst($realFile, 1);
  721. }
  722. $this->complete();
  723. return true;
  724. }
  725. /**
  726. * 生成
  727. * @return bool
  728. * @throws Exception
  729. * @throws \yii\base\InvalidConfigException
  730. * @throws \yii\httpclient\Exception
  731. */
  732. public function generateDecOrderPDF() {
  733. $this->getParams();
  734. if (!$this->params) {
  735. throw new Exception('无法获取需要的参数');
  736. }
  737. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  738. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  739. $this->completed = false;
  740. $this->getExportId();
  741. $this->getUserId();
  742. $fileNameUpdated = false;
  743. // 获取列表数据及表头
  744. $this->_listModel = new $this->listModelClass();
  745. $this->_listModel->isExport = true;
  746. // 查询订单数据
  747. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  748. $orderQuery = Order::find()
  749. ->alias('O')
  750. ->where($this->params['condition'], $this->params['params'])
  751. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  752. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  753. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  754. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  755. ->orderBy('O.CREATED_AT DESC');
  756. // 订单中间表只查询待支付和支付失败的订单
  757. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  758. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  759. $orderStandardQuery = ApproachOrder::find()
  760. ->alias('O')
  761. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  762. ->select('O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
  763. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  764. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  765. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  766. ->orderBy('O.CREATED_AT DESC');
  767. $queryAll = $orderQuery->union($orderStandardQuery, true);
  768. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  769. $oderList = $query->all();
  770. if ($oderList) {
  771. $userId = '';
  772. $userName = '';
  773. $address = '';
  774. $mobile = '';
  775. $orderAt = '';
  776. $orderDetails = '';
  777. $orderSn = '';
  778. $orderAmount = 0; // 合计总额
  779. $orderNums = 0; // 合计总数
  780. $totalTaxAmount = 0; // 合计税额
  781. $totalAmount = 0;
  782. foreach ($oderList as $key => $value) {
  783. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  784. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  785. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  786. $userId = $value['USER_NAME'];
  787. $userName = $value['REAL_NAME'];
  788. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  789. $mobile = $value['MOBILE'];
  790. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  791. $orderSn = $value['SN'];
  792. // 总价
  793. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  794. $orderAmount += $totalAmount;
  795. $orderNums += $value['BUY_NUMS'];
  796. // 税额
  797. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  798. $totalTaxAmount += $taxAmount;
  799. $taxAmount = Tool::formatAmount($taxAmount);
  800. $totalAmount = Tool::formatAmount($totalAmount);
  801. // 订单详情
  802. $orderDetails .= <<<EOT
  803. <tr>
  804. <td>{$value['SKU_CODE']}</td>
  805. <td>{$value['GOODS_TITLE']}</td>
  806. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  807. <td>{$value['BUY_NUMS']}</td>
  808. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  809. <td style="text-align: right;">{$taxAmount}</td>
  810. <td style="text-align: right;">{$totalAmount}</td>
  811. </tr>
  812. EOT;
  813. }
  814. // 订单基本信息
  815. $orderBase = <<<ORDER
  816. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  817. <tr>
  818. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member code</td>
  819. <td width="70%">{$userId}</td>
  820. </tr>
  821. <tr>
  822. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member name</td>
  823. <td width="70%">{$userName}</td>
  824. </tr>
  825. <tr>
  826. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member address</td>
  827. <td width="70%">{$address}</td>
  828. </tr>
  829. <tr>
  830. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member phone</td>
  831. <td width="70%">{$mobile}</td>
  832. </tr>
  833. <tr>
  834. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order code</td>
  835. <td width="70%">{$orderSn}</td>
  836. </tr>
  837. <tr>
  838. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation time</td>
  839. <td width="70%">{$orderAt}</td>
  840. </tr>
  841. <tr>
  842. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order detail</td>
  843. <td class="bg"></td>
  844. </tr>
  845. </table>
  846. ORDER;
  847. $l['a_meta_charset'] = 'UTF-8';
  848. $l['a_meta_dir'] = 'ltr';
  849. $l['a_meta_language'] = 'zh';
  850. $l['w_page'] = '页面';
  851. $orderAmount = Tool::formatAmount($orderAmount);
  852. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  853. $context = <<<ORDER
  854. <!doctype html>
  855. <html lang="en">
  856. <head>
  857. <meta charset="UTF-8" />
  858. <title>Order detail</title>
  859. <style>
  860. table {
  861. border-collapse: collapse;
  862. }
  863. table td, table th {
  864. border: 1px solid #ccc;
  865. padding: 5px 5px;
  866. border-collapse: collapse;
  867. }
  868. /*td {*/
  869. /* padding: 120px;*/
  870. /*}*/
  871. .bg {
  872. background-color: #ccc;
  873. }
  874. </style>
  875. </head>
  876. <body>
  877. <div class="content">
  878. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  879. <div>
  880. <div style="display: block; width: 100%;">
  881. {$orderBase}
  882. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  883. <tr>
  884. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product code</th>
  885. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product name</th>
  886. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product price</th>
  887. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  888. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax rate</th>
  889. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  890. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total amount</th>
  891. </tr>
  892. {$orderDetails}
  893. <tr>
  894. <td colspan="3">Total</td>
  895. <td>{$orderNums}</td>
  896. <td></td>
  897. <td style="text-align: right;">{$totalTaxAmount}</td>
  898. <td style="text-align: right;">{$orderAmount}</td>
  899. </tr>
  900. </table>
  901. </div>
  902. <div style="width: 100%; margin-top: 50px; height: 30px;">
  903. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  904. <tr style="border: none;">
  905. <td width="70%" style="border: none;"></td>
  906. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  907. </tr>
  908. <tr style="border: none;">
  909. <td width="70%" style="border: none;"></td>
  910. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  911. </tr>
  912. </table>
  913. </div>
  914. </div>
  915. </div>
  916. </body>
  917. </html>
  918. ORDER;
  919. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  920. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  921. // 设置打印模式
  922. $pdf->SetCreator(PDF_CREATOR);
  923. $pdf->SetAuthor('DaZe');
  924. $pdf->SetTitle($orderSn);
  925. $pdf->SetSubject('TCPDF Tutorial');
  926. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  927. // 是否显示页眉
  928. $pdf->setPrintHeader(false);
  929. // 设置页眉字体
  930. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  931. // 页眉距离顶部的距离
  932. $pdf->SetHeaderMargin('5');
  933. // 是否显示页脚
  934. $pdf->setPrintFooter(false);
  935. // 设置默认等宽字体
  936. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  937. // 设置行高
  938. $pdf->setCellHeightRatio(1);
  939. // 设置左、上、右的间距
  940. $pdf->SetMargins('10', '10', '10');
  941. // 设置是否自动分页 距离底部多少距离时分页
  942. $pdf->SetAutoPageBreak(TRUE, '15');
  943. // 设置图像比例因子
  944. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  945. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  946. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  947. $pdf->setLanguageArray($l);
  948. }
  949. $pdf->setFontSubsetting(true);
  950. $pdf->AddPage();
  951. // 设置字体
  952. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  953. $pdf->writeHTML($context);
  954. $pdf->Output($realFile, 'F');
  955. $this->_updateFirst($realFile, 1);
  956. }
  957. $this->complete();
  958. return true;
  959. }
  960. /**
  961. * 循环写入数据
  962. * @param $realFile
  963. * @param $fileNameUpdated
  964. * @param int $page
  965. * @param int $counter
  966. * @return array
  967. * @throws Exception
  968. */
  969. private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  970. if(method_exists($this->_listModel, 'getList')){
  971. $list = $this->_listModel->getList(['condition'=>$this->params['condition'], 'params'=>isset($this->params['params']) ? $this->params['params'] : [], 'others'=>isset($this->params['others']) ? $this->params['others'] : [], 'page'=>$page, 'pageSize'=>$this->pageSize, 'userId'=>$this->userId]);
  972. } else {
  973. throw new Exception($this->listModelClass.'的getList方法不存在');
  974. }
  975. return $list['list'];
  976. }
  977. }