BaseExport.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. $orderQuery = Order::find()
  285. ->alias('O')
  286. ->where($this->params['condition'], $this->params['params'])
  287. ->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')
  288. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  289. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  290. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  291. ->orderBy('O.CREATED_AT DESC');
  292. // 订单中间表只查询待支付和支付失败的订单
  293. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  294. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  295. $orderStandardQuery = ApproachOrder::find()
  296. ->alias('O')
  297. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  298. ->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')
  299. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  300. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  301. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  302. ->orderBy('O.CREATED_AT DESC');
  303. $queryAll = $orderQuery->union($orderStandardQuery, true);
  304. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  305. $lists = $query->all();
  306. if(!empty($lists)){
  307. foreach($lists as $columnData){
  308. fputcsv($this->_fp, Tool::arrTextConvert($columnData));
  309. unset($percent, $columnData);
  310. }
  311. unset($list);
  312. }
  313. unset($list);
  314. return 'finish';
  315. }
  316. /**
  317. * 完成
  318. * @return bool
  319. * @throws Exception
  320. * @throws \yii\base\InvalidConfigException
  321. * @throws \yii\httpclient\Exception
  322. */
  323. public function complete() {
  324. $this->_updatePercent(100);
  325. if ($this->completed) {
  326. return true;
  327. }
  328. if ($this->_fp) {
  329. fclose($this->_fp);
  330. }
  331. // 把导出的文件上传至静态文件服务器
  332. if ($this->isRemote) {
  333. $realFile = $this->getSaveBasePath() . __DS__ . $this->getSavePath() . __DS__ . $this->getFileName();
  334. $remoteUploadApi = RemoteUploadApi::instance();
  335. if ($uploadResult = $remoteUploadApi->upload($realFile)) {
  336. Export::updateAll(['REMOTE_URL' => $uploadResult['url'], 'IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  337. } else {
  338. $this->_errorHandle();
  339. throw new Exception('文件远程上传失败');
  340. }
  341. // 删除本地临时文件
  342. unlink($realFile);
  343. } else {
  344. Export::updateAll(['IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  345. }
  346. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin(100, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  347. CacheHelper::deleteAsyncParams($this->taskId);
  348. $this->completed = true;
  349. }
  350. /**
  351. * @param $message
  352. */
  353. private function _errorNotice($message) {
  354. Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($this->userId, $message, false);
  355. }
  356. /**
  357. * 首次更新
  358. * @param $exportId
  359. * @param $realName
  360. */
  361. private function _updateFirst($realName, $percent) {
  362. $fileName = str_replace($this->getSaveBasePath() . __DS__, '', $realName);
  363. Export::updateAll([
  364. 'FILE_NAME' => str_replace(__DS__, '/', $fileName),
  365. 'UPDATED_AT' => Date::nowTime(),
  366. 'EXPORT_PERCENT' => $percent,
  367. ], 'ID=:ID', [':ID' => $this->exportId]);
  368. }
  369. /**
  370. * 更新百分比
  371. * @param $exportId
  372. * @param $percent
  373. */
  374. private function _updatePercent($percent) {
  375. // 把数据写入数据库中
  376. Export::updateAll(['EXPORT_PERCENT' => $percent], 'ID=:ID', [':ID' => $this->exportId]);
  377. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  378. }
  379. /**
  380. * 发生错误处理
  381. * @param $exportId
  382. */
  383. private function _errorHandle() {
  384. Export::updateAll(['IS_EXPORTING' => 0], 'ID=:ID', [':ID' => $this->exportId]);
  385. }
  386. /**
  387. * 导出逻辑
  388. * @param $filter
  389. * @param $listName
  390. * @param null $consoleRouter
  391. * @throws Exception
  392. */
  393. public function exportHandle($filter, $listName, $consoleRouter = null){
  394. $params = [
  395. 'moduleId' => $this->moduleId,
  396. 'listName' => $listName,
  397. 'action' => $consoleRouter ? $consoleRouter : Yii::$app->controller->id.'/'.Yii::$app->controller->action->id, // 这里这么写,是因为调用的异步路由和同步的控制器和方法是一样的,所以,只要不传默认调和同步一样的异步方法
  398. 'userId' => Yii::$app->user->id,
  399. ];
  400. $this->webToAsync($params,$filter);
  401. }
  402. /**
  403. * 页面到异步的请求
  404. * @param $params
  405. * @param array $extend
  406. * @return bool
  407. * @throws Exception
  408. */
  409. public function webToAsync($params, $extend = []) {
  410. $default = [
  411. 'moduleId' => null,
  412. 'listName' => null,
  413. 'remark' => null,
  414. 'action' => null,
  415. 'userId' => null,
  416. ];
  417. $params = Tool::deepParse($params, $default);
  418. if (!$params['moduleId'] || !$params['listName'] || !$params['action']) {
  419. throw new Exception('请设置moduleId,listName和action');
  420. }
  421. // 把文件对应的相关资料存入数据库中
  422. $export = new Export();
  423. $export->EXPORT_NAME = $params['listName'] . '_' . date('y年m月d日H时i分s秒导出', Date::nowTime());
  424. $export->MODULE_NAME = $params['moduleId'];
  425. $export->REMARK = $params['remark'];
  426. $export->IS_EXPORTING = 1;
  427. $export->ADMIN_ID = \Yii::$app->user->id;
  428. $export->STARTED_AT = Date::nowTime();
  429. $export->CREATED_AT = Date::nowTime();
  430. $export->EXPORT_PERCENT = 0;
  431. $export->ENDED_AT = 0;
  432. $export->UPDATED_AT = 0;
  433. if (!$export->save()) {
  434. throw new Exception(Form::formatErrorsForApi($export->getErrors()));
  435. }
  436. $extend = array_merge($extend, [
  437. 'exportId' => $export->ID,
  438. 'userId' => $params['userId'],
  439. ]);
  440. // 异步处理添加任务
  441. $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle($params['action'], $extend);
  442. if($taskKey === false){
  443. // 删除刚刚添加的导出数据
  444. Export::deleteAll(['ID'=>$export->ID]);
  445. throw new Exception('导出失败,请求异步处理服务器失败');
  446. }
  447. return $taskKey;
  448. }
  449. /**
  450. * 生成
  451. * @return bool
  452. * @throws Exception
  453. * @throws \yii\base\InvalidConfigException
  454. * @throws \yii\httpclient\Exception
  455. */
  456. public function generateOrderExcel() {
  457. $this->getParams();
  458. if (!$this->params) {
  459. throw new Exception('无法获取需要的参数');
  460. }
  461. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  462. $path = __DS__ . $path;
  463. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  464. $this->completed = false;
  465. $this->getExportId();
  466. $this->getUserId();
  467. $fileNameUpdated = false;
  468. $this->_fp = fopen($realFile, 'w');
  469. @exec('chown -R www:www /'.$realFile);
  470. @exec('chmod -R 777 /'.$realFile);
  471. // 获取列表数据及表头
  472. $this->_listModel = new $this->listModelClass();
  473. $this->_listModel->isExport = true;
  474. if(method_exists($this->_listModel, 'getExportHeaders')){
  475. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  476. $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]);
  477. }
  478. $headers = $this->_listModel->getExportHeaders($this->userId);
  479. fputcsv($this->_fp, $headers);
  480. unset($headers);
  481. $this->_updateFirst($realFile, 1);
  482. } else {
  483. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  484. }
  485. $this->_loopWriteDataOrder();
  486. $this->complete();
  487. return true;
  488. }
  489. /**
  490. * 生成
  491. * @return bool
  492. * @throws Exception
  493. * @throws \yii\base\InvalidConfigException
  494. * @throws \yii\httpclient\Exception
  495. */
  496. public function generateOrderPDF() {
  497. $this->getParams();
  498. if (!$this->params) {
  499. throw new Exception('无法获取需要的参数');
  500. }
  501. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  502. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  503. $this->completed = false;
  504. $this->getExportId();
  505. $this->getUserId();
  506. $fileNameUpdated = false;
  507. // 获取列表数据及表头
  508. $this->_listModel = new $this->listModelClass();
  509. $this->_listModel->isExport = true;
  510. // 查询订单数据
  511. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  512. $orderQuery = Order::find()
  513. ->alias('O')
  514. ->where($this->params['condition'], $this->params['params'])
  515. ->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')
  516. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  517. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  518. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  519. ->orderBy('O.CREATED_AT DESC');
  520. // 订单中间表只查询待支付和支付失败的订单
  521. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  522. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  523. $orderStandardQuery = ApproachOrder::find()
  524. ->alias('O')
  525. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  526. ->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')
  527. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  528. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  529. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  530. ->orderBy('O.CREATED_AT DESC');
  531. $queryAll = $orderQuery->union($orderStandardQuery, true);
  532. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  533. $oderList = $query->all();
  534. if ($oderList) {
  535. $userId = '';
  536. $userName = '';
  537. $address = '';
  538. $mobile = '';
  539. $orderAt = '';
  540. $orderDetails = '';
  541. $orderSn = '';
  542. $orderAmount = 0; // 合计总额
  543. $orderNums = 0; // 合计总数
  544. $totalTaxAmount = 0; // 合计税额
  545. $totalAmount = 0;
  546. foreach ($oderList as $key => $value) {
  547. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  548. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  549. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  550. $userId = $value['USER_NAME'];
  551. $userName = $value['REAL_NAME'];
  552. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  553. $mobile = $value['MOBILE'];
  554. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  555. $orderSn = $value['SN'];
  556. // 总价
  557. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  558. $orderAmount += $totalAmount;
  559. $orderNums += $value['BUY_NUMS'];
  560. // 税额
  561. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  562. $totalTaxAmount += $taxAmount;
  563. $taxAmount = Tool::formatAmount($taxAmount);
  564. $totalAmount = Tool::formatAmount($totalAmount);
  565. // 订单详情
  566. $orderDetails .= <<<EOT
  567. <tr>
  568. <td>{$value['SKU_CODE']}</td>
  569. <td>{$value['GOODS_TITLE']}</td>
  570. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  571. <td>{$value['BUY_NUMS']}</td>
  572. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  573. <td style="text-align: right;">{$taxAmount}</td>
  574. <td style="text-align: right;">{$totalAmount}</td>
  575. </tr>
  576. EOT;
  577. }
  578. // 订单基本信息
  579. $orderBase = <<<ORDER
  580. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  581. <tr>
  582. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member code</td>
  583. <td width="70%">{$userId}</td>
  584. </tr>
  585. <tr>
  586. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member name</td>
  587. <td width="70%">{$userName}</td>
  588. </tr>
  589. <tr>
  590. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member address</td>
  591. <td width="70%">{$address}</td>
  592. </tr>
  593. <tr>
  594. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member phone</td>
  595. <td width="70%">{$mobile}</td>
  596. </tr>
  597. <tr>
  598. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order code</td>
  599. <td width="70%">{$orderSn}</td>
  600. </tr>
  601. <tr>
  602. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation time</td>
  603. <td width="70%">{$orderAt}</td>
  604. </tr>
  605. <tr>
  606. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order detail</td>
  607. <td class="bg"></td>
  608. </tr>
  609. </table>
  610. ORDER;
  611. $l['a_meta_charset'] = 'UTF-8';
  612. $l['a_meta_dir'] = 'ltr';
  613. $l['a_meta_language'] = 'zh';
  614. $l['w_page'] = '页面';
  615. $orderAmount = Tool::formatAmount($orderAmount);
  616. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  617. $context = <<<ORDER
  618. <!doctype html>
  619. <html lang="en">
  620. <head>
  621. <meta charset="UTF-8" />
  622. <title>Order detail</title>
  623. <style>
  624. table {
  625. border-collapse: collapse;
  626. }
  627. table td, table th {
  628. border: 1px solid #ccc;
  629. padding: 5px 5px;
  630. border-collapse: collapse;
  631. }
  632. /*td {*/
  633. /* padding: 120px;*/
  634. /*}*/
  635. .bg {
  636. background-color: #ccc;
  637. }
  638. </style>
  639. </head>
  640. <body>
  641. <div class="content">
  642. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  643. <div>
  644. <div style="display: block; width: 100%;">
  645. {$orderBase}
  646. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  647. <tr>
  648. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product code</th>
  649. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product name</th>
  650. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product price</th>
  651. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  652. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax rate</th>
  653. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  654. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total amount</th>
  655. </tr>
  656. {$orderDetails}
  657. <tr>
  658. <td colspan="3">Total</td>
  659. <td>{$orderNums}</td>
  660. <td></td>
  661. <td style="text-align: right;">{$totalTaxAmount}</td>
  662. <td style="text-align: right;">{$orderAmount}</td>
  663. </tr>
  664. </table>
  665. </div>
  666. <div style="width: 100%; margin-top: 50px; height: 30px;">
  667. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  668. <tr style="border: none;">
  669. <td width="70%" style="border: none;"></td>
  670. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  671. </tr>
  672. <tr style="border: none;">
  673. <td width="70%" style="border: none;"></td>
  674. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  675. </tr>
  676. </table>
  677. </div>
  678. </div>
  679. </div>
  680. </body>
  681. </html>
  682. ORDER;
  683. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  684. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  685. // 设置打印模式
  686. $pdf->SetCreator(PDF_CREATOR);
  687. $pdf->SetAuthor('DaZe');
  688. $pdf->SetTitle($orderSn);
  689. $pdf->SetSubject('TCPDF Tutorial');
  690. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  691. // 是否显示页眉
  692. $pdf->setPrintHeader(false);
  693. // 设置页眉字体
  694. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  695. // 页眉距离顶部的距离
  696. $pdf->SetHeaderMargin('5');
  697. // 是否显示页脚
  698. $pdf->setPrintFooter(false);
  699. // 设置默认等宽字体
  700. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  701. // 设置行高
  702. $pdf->setCellHeightRatio(1);
  703. // 设置左、上、右的间距
  704. $pdf->SetMargins('10', '10', '10');
  705. // 设置是否自动分页 距离底部多少距离时分页
  706. $pdf->SetAutoPageBreak(TRUE, '15');
  707. // 设置图像比例因子
  708. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  709. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  710. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  711. $pdf->setLanguageArray($l);
  712. }
  713. $pdf->setFontSubsetting(true);
  714. $pdf->AddPage();
  715. // 设置字体
  716. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  717. $pdf->writeHTML($context);
  718. $pdf->Output($realFile, 'F');
  719. $this->_updateFirst($realFile, 1);
  720. }
  721. $this->complete();
  722. return true;
  723. }
  724. /**
  725. * 生成
  726. * @return bool
  727. * @throws Exception
  728. * @throws \yii\base\InvalidConfigException
  729. * @throws \yii\httpclient\Exception
  730. */
  731. public function generateDecOrderPDF() {
  732. $this->getParams();
  733. if (!$this->params) {
  734. throw new Exception('无法获取需要的参数');
  735. }
  736. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  737. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  738. $this->completed = false;
  739. $this->getExportId();
  740. $this->getUserId();
  741. $fileNameUpdated = false;
  742. // 获取列表数据及表头
  743. $this->_listModel = new $this->listModelClass();
  744. $this->_listModel->isExport = true;
  745. // 查询订单数据
  746. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  747. $orderQuery = Order::find()
  748. ->alias('O')
  749. ->where($this->params['condition'], $this->params['params'])
  750. ->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')
  751. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  752. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  753. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  754. ->orderBy('O.CREATED_AT DESC');
  755. // 订单中间表只查询待支付和支付失败的订单
  756. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  757. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  758. $orderStandardQuery = ApproachOrder::find()
  759. ->alias('O')
  760. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  761. ->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')
  762. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  763. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  764. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  765. ->orderBy('O.CREATED_AT DESC');
  766. $queryAll = $orderQuery->union($orderStandardQuery, true);
  767. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  768. $oderList = $query->all();
  769. if ($oderList) {
  770. $userId = '';
  771. $userName = '';
  772. $address = '';
  773. $mobile = '';
  774. $orderAt = '';
  775. $orderDetails = '';
  776. $orderSn = '';
  777. $orderAmount = 0; // 合计总额
  778. $orderNums = 0; // 合计总数
  779. $totalTaxAmount = 0; // 合计税额
  780. $totalAmount = 0;
  781. foreach ($oderList as $key => $value) {
  782. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  783. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  784. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  785. $userId = $value['USER_NAME'];
  786. $userName = $value['REAL_NAME'];
  787. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  788. $mobile = $value['MOBILE'];
  789. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  790. $orderSn = $value['SN'];
  791. // 总价
  792. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  793. $orderAmount += $totalAmount;
  794. $orderNums += $value['BUY_NUMS'];
  795. // 税额
  796. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  797. $totalTaxAmount += $taxAmount;
  798. $taxAmount = Tool::formatAmount($taxAmount);
  799. $totalAmount = Tool::formatAmount($totalAmount);
  800. // 订单详情
  801. $orderDetails .= <<<EOT
  802. <tr>
  803. <td>{$value['SKU_CODE']}</td>
  804. <td>{$value['GOODS_TITLE']}</td>
  805. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  806. <td>{$value['BUY_NUMS']}</td>
  807. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  808. <td style="text-align: right;">{$taxAmount}</td>
  809. <td style="text-align: right;">{$totalAmount}</td>
  810. </tr>
  811. EOT;
  812. }
  813. // 订单基本信息
  814. $orderBase = <<<ORDER
  815. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  816. <tr>
  817. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member code</td>
  818. <td width="70%">{$userId}</td>
  819. </tr>
  820. <tr>
  821. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member name</td>
  822. <td width="70%">{$userName}</td>
  823. </tr>
  824. <tr>
  825. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member address</td>
  826. <td width="70%">{$address}</td>
  827. </tr>
  828. <tr>
  829. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member phone</td>
  830. <td width="70%">{$mobile}</td>
  831. </tr>
  832. <tr>
  833. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order code</td>
  834. <td width="70%">{$orderSn}</td>
  835. </tr>
  836. <tr>
  837. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation time</td>
  838. <td width="70%">{$orderAt}</td>
  839. </tr>
  840. <tr>
  841. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order detail</td>
  842. <td class="bg"></td>
  843. </tr>
  844. </table>
  845. ORDER;
  846. $l['a_meta_charset'] = 'UTF-8';
  847. $l['a_meta_dir'] = 'ltr';
  848. $l['a_meta_language'] = 'zh';
  849. $l['w_page'] = '页面';
  850. $orderAmount = Tool::formatAmount($orderAmount);
  851. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  852. $context = <<<ORDER
  853. <!doctype html>
  854. <html lang="en">
  855. <head>
  856. <meta charset="UTF-8" />
  857. <title>Order detail</title>
  858. <style>
  859. table {
  860. border-collapse: collapse;
  861. }
  862. table td, table th {
  863. border: 1px solid #ccc;
  864. padding: 5px 5px;
  865. border-collapse: collapse;
  866. }
  867. /*td {*/
  868. /* padding: 120px;*/
  869. /*}*/
  870. .bg {
  871. background-color: #ccc;
  872. }
  873. </style>
  874. </head>
  875. <body>
  876. <div class="content">
  877. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  878. <div>
  879. <div style="display: block; width: 100%;">
  880. {$orderBase}
  881. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  882. <tr>
  883. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product code</th>
  884. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product name</th>
  885. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product price</th>
  886. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  887. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax rate</th>
  888. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  889. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total amount</th>
  890. </tr>
  891. {$orderDetails}
  892. <tr>
  893. <td colspan="3">Total</td>
  894. <td>{$orderNums}</td>
  895. <td></td>
  896. <td style="text-align: right;">{$totalTaxAmount}</td>
  897. <td style="text-align: right;">{$orderAmount}</td>
  898. </tr>
  899. </table>
  900. </div>
  901. <div style="width: 100%; margin-top: 50px; height: 30px;">
  902. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  903. <tr style="border: none;">
  904. <td width="70%" style="border: none;"></td>
  905. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  906. </tr>
  907. <tr style="border: none;">
  908. <td width="70%" style="border: none;"></td>
  909. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  910. </tr>
  911. </table>
  912. </div>
  913. </div>
  914. </div>
  915. </body>
  916. </html>
  917. ORDER;
  918. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  919. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  920. // 设置打印模式
  921. $pdf->SetCreator(PDF_CREATOR);
  922. $pdf->SetAuthor('DaZe');
  923. $pdf->SetTitle($orderSn);
  924. $pdf->SetSubject('TCPDF Tutorial');
  925. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  926. // 是否显示页眉
  927. $pdf->setPrintHeader(false);
  928. // 设置页眉字体
  929. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  930. // 页眉距离顶部的距离
  931. $pdf->SetHeaderMargin('5');
  932. // 是否显示页脚
  933. $pdf->setPrintFooter(false);
  934. // 设置默认等宽字体
  935. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  936. // 设置行高
  937. $pdf->setCellHeightRatio(1);
  938. // 设置左、上、右的间距
  939. $pdf->SetMargins('10', '10', '10');
  940. // 设置是否自动分页 距离底部多少距离时分页
  941. $pdf->SetAutoPageBreak(TRUE, '15');
  942. // 设置图像比例因子
  943. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  944. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  945. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  946. $pdf->setLanguageArray($l);
  947. }
  948. $pdf->setFontSubsetting(true);
  949. $pdf->AddPage();
  950. // 设置字体
  951. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  952. $pdf->writeHTML($context);
  953. $pdf->Output($realFile, 'F');
  954. $this->_updateFirst($realFile, 1);
  955. }
  956. $this->complete();
  957. return true;
  958. }
  959. /**
  960. * 循环写入数据
  961. * @param $realFile
  962. * @param $fileNameUpdated
  963. * @param int $page
  964. * @param int $counter
  965. * @return array
  966. * @throws Exception
  967. */
  968. private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  969. if(method_exists($this->_listModel, 'getList')){
  970. $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]);
  971. } else {
  972. throw new Exception($this->listModelClass.'的getList方法不存在');
  973. }
  974. return $list['list'];
  975. }
  976. }