BaseExport.php 52 KB

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