BaseExport.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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')
  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')
  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' => $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']) ? 'Reselling': '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' => Date('Y-m-d H:i:s', $columnData['PAY_AT']),
  337. 'DELIVERY_AT' => Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']),
  338. 'REAL_PRICE' => $columnData['REAL_PRICE'],
  339. 'REAL_PV' => $columnData['REAL_PV'],
  340. 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'],
  341. 'TAX_RATE' => $columnData['TAX_RATE'],
  342. 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
  343. 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
  344. 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
  345. 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
  346. 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
  347. 'DELIVERY_STATUS_NAME' => \Yii::$app->params['deliveryStatus'][$columnData['DELIVERY_STATUS']]['label'] ?? '',
  348. 'IS_AUTO' => $columnData['IS_AUTO'] == 1 ? 'Yes' : 'No',
  349. ];
  350. fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
  351. unset($percent, $columnData, $columnAccept);
  352. }
  353. unset($list);
  354. }
  355. unset($list);
  356. return 'finish';
  357. }
  358. /**
  359. * 完成
  360. * @return bool
  361. * @throws Exception
  362. * @throws \yii\base\InvalidConfigException
  363. * @throws \yii\httpclient\Exception
  364. */
  365. public function complete() {
  366. $this->_updatePercent(100);
  367. if ($this->completed) {
  368. return true;
  369. }
  370. if ($this->_fp) {
  371. fclose($this->_fp);
  372. }
  373. // 把导出的文件上传至静态文件服务器
  374. if ($this->isRemote) {
  375. $realFile = $this->getSaveBasePath() . __DS__ . $this->getSavePath() . __DS__ . $this->getFileName();
  376. $remoteUploadApi = RemoteUploadApi::instance();
  377. if ($uploadResult = $remoteUploadApi->upload($realFile)) {
  378. Export::updateAll(['REMOTE_URL' => $uploadResult['url'], 'IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  379. } else {
  380. $this->_errorHandle();
  381. throw new Exception('文件远程上传失败');
  382. }
  383. // 删除本地临时文件
  384. unlink($realFile);
  385. } else {
  386. Export::updateAll(['IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  387. }
  388. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin(100, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  389. CacheHelper::deleteAsyncParams($this->taskId);
  390. $this->completed = true;
  391. }
  392. /**
  393. * @param $message
  394. */
  395. private function _errorNotice($message) {
  396. Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($this->userId, $message, false);
  397. }
  398. /**
  399. * 首次更新
  400. * @param $exportId
  401. * @param $realName
  402. */
  403. private function _updateFirst($realName, $percent) {
  404. $fileName = str_replace($this->getSaveBasePath() . __DS__, '', $realName);
  405. Export::updateAll([
  406. 'FILE_NAME' => str_replace(__DS__, '/', $fileName),
  407. 'UPDATED_AT' => Date::nowTime(),
  408. 'EXPORT_PERCENT' => $percent,
  409. ], 'ID=:ID', [':ID' => $this->exportId]);
  410. }
  411. /**
  412. * 更新百分比
  413. * @param $exportId
  414. * @param $percent
  415. */
  416. private function _updatePercent($percent) {
  417. // 把数据写入数据库中
  418. Export::updateAll(['EXPORT_PERCENT' => $percent], 'ID=:ID', [':ID' => $this->exportId]);
  419. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  420. }
  421. /**
  422. * 发生错误处理
  423. * @param $exportId
  424. */
  425. private function _errorHandle() {
  426. Export::updateAll(['IS_EXPORTING' => 0], 'ID=:ID', [':ID' => $this->exportId]);
  427. }
  428. /**
  429. * 导出逻辑
  430. * @param $filter
  431. * @param $listName
  432. * @param null $consoleRouter
  433. * @throws Exception
  434. */
  435. public function exportHandle($filter, $listName, $consoleRouter = null){
  436. $params = [
  437. 'moduleId' => $this->moduleId,
  438. 'listName' => $listName,
  439. 'action' => $consoleRouter ? $consoleRouter : Yii::$app->controller->id.'/'.Yii::$app->controller->action->id, // 这里这么写,是因为调用的异步路由和同步的控制器和方法是一样的,所以,只要不传默认调和同步一样的异步方法
  440. 'userId' => Yii::$app->user->id,
  441. ];
  442. $this->webToAsync($params,$filter);
  443. }
  444. /**
  445. * 页面到异步的请求
  446. * @param $params
  447. * @param array $extend
  448. * @return bool
  449. * @throws Exception
  450. */
  451. public function webToAsync($params, $extend = []) {
  452. $default = [
  453. 'moduleId' => null,
  454. 'listName' => null,
  455. 'remark' => null,
  456. 'action' => null,
  457. 'userId' => null,
  458. ];
  459. $params = Tool::deepParse($params, $default);
  460. if (!$params['moduleId'] || !$params['listName'] || !$params['action']) {
  461. throw new Exception('请设置moduleId,listName和action');
  462. }
  463. // 把文件对应的相关资料存入数据库中
  464. $export = new Export();
  465. $export->EXPORT_NAME = $params['listName'] . '_' . date('Exp_y-m-d H:i:s', Date::nowTime());
  466. $export->MODULE_NAME = $params['moduleId'];
  467. $export->REMARK = $params['remark'];
  468. $export->IS_EXPORTING = 1;
  469. $export->ADMIN_ID = \Yii::$app->user->id;
  470. $export->STARTED_AT = Date::nowTime();
  471. $export->CREATED_AT = Date::nowTime();
  472. $export->EXPORT_PERCENT = 0;
  473. $export->ENDED_AT = 0;
  474. $export->UPDATED_AT = 0;
  475. if (!$export->save()) {
  476. throw new Exception(Form::formatErrorsForApi($export->getErrors()));
  477. }
  478. $extend = array_merge($extend, [
  479. 'exportId' => $export->ID,
  480. 'userId' => $params['userId'],
  481. ]);
  482. // 异步处理添加任务
  483. $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle($params['action'], $extend);
  484. if($taskKey === false){
  485. // 删除刚刚添加的导出数据
  486. Export::deleteAll(['ID'=>$export->ID]);
  487. throw new Exception('导出失败,请求异步处理服务器失败');
  488. }
  489. return $taskKey;
  490. }
  491. /**
  492. * 生成
  493. * @return bool
  494. * @throws Exception
  495. * @throws \yii\base\InvalidConfigException
  496. * @throws \yii\httpclient\Exception
  497. */
  498. public function generateOrderExcel() {
  499. $this->getParams();
  500. if (!$this->params) {
  501. throw new Exception('无法获取需要的参数');
  502. }
  503. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  504. $path = __DS__ . $path;
  505. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  506. $this->completed = false;
  507. $this->getExportId();
  508. $this->getUserId();
  509. $fileNameUpdated = false;
  510. $this->_fp = fopen($realFile, 'w');
  511. @exec('chown -R www:www /'.$realFile);
  512. @exec('chmod -R 777 /'.$realFile);
  513. // 获取列表数据及表头
  514. $this->_listModel = new $this->listModelClass();
  515. $this->_listModel->isExport = true;
  516. if(method_exists($this->_listModel, 'getExportHeaders')){
  517. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  518. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
  519. }
  520. $headers = $this->_listModel->getExportHeaders($this->userId);
  521. fputcsv($this->_fp, $headers);
  522. unset($headers);
  523. $this->_updateFirst($realFile, 1);
  524. } else {
  525. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  526. }
  527. $this->_loopWriteDataOrder();
  528. $this->complete();
  529. return true;
  530. }
  531. /**
  532. * 生成
  533. * @return bool
  534. * @throws Exception
  535. * @throws \yii\base\InvalidConfigException
  536. * @throws \yii\httpclient\Exception
  537. */
  538. public function generateOrderPDF() {
  539. $this->getParams();
  540. if (!$this->params) {
  541. throw new Exception('无法获取需要的参数');
  542. }
  543. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  544. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  545. $this->completed = false;
  546. $this->getExportId();
  547. $this->getUserId();
  548. $fileNameUpdated = false;
  549. // 获取列表数据及表头
  550. $this->_listModel = new $this->listModelClass();
  551. $this->_listModel->isExport = true;
  552. // 查询订单数据
  553. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  554. $orderQuery = Order::find()
  555. ->alias('O')
  556. ->where($this->params['condition'], $this->params['params'])
  557. ->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')
  558. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  559. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  560. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  561. ->orderBy('O.CREATED_AT DESC');
  562. // 订单中间表只查询待支付和支付失败的订单
  563. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  564. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  565. $orderStandardQuery = ApproachOrder::find()
  566. ->alias('O')
  567. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  568. ->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')
  569. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  570. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  571. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  572. ->orderBy('O.CREATED_AT DESC');
  573. $queryAll = $orderQuery->union($orderStandardQuery, true);
  574. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  575. $oderList = $query->all();
  576. if ($oderList) {
  577. $userId = '';
  578. $userName = '';
  579. $address = '';
  580. $mobile = '';
  581. $orderAt = '';
  582. $orderDetails = '';
  583. $orderSn = '';
  584. $orderAmount = 0; // 合计总额
  585. $orderNums = 0; // 合计总数
  586. $totalTaxAmount = 0; // 合计税额
  587. $totalAmount = 0;
  588. foreach ($oderList as $key => $value) {
  589. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  590. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  591. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  592. $userId = $value['USER_NAME'];
  593. $userName = $value['REAL_NAME'];
  594. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  595. $mobile = $value['MOBILE'];
  596. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  597. $orderSn = $value['SN'];
  598. // 总价
  599. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  600. $orderAmount += $totalAmount;
  601. $orderNums += $value['BUY_NUMS'];
  602. // 税额
  603. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  604. $totalTaxAmount += $taxAmount;
  605. $taxAmount = Tool::formatAmount($taxAmount);
  606. $totalAmount = Tool::formatAmount($totalAmount);
  607. // 订单详情
  608. $orderDetails .= <<<EOT
  609. <tr>
  610. <td>{$value['SKU_CODE']}</td>
  611. <td>{$value['GOODS_TITLE']}</td>
  612. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  613. <td>{$value['BUY_NUMS']}</td>
  614. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  615. <td style="text-align: right;">{$taxAmount}</td>
  616. <td style="text-align: right;">{$totalAmount}</td>
  617. </tr>
  618. EOT;
  619. }
  620. // 订单基本信息
  621. $orderBase = <<<ORDER
  622. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  623. <tr>
  624. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
  625. <td width="70%">{$userId}</td>
  626. </tr>
  627. <tr>
  628. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
  629. <td width="70%">{$userName}</td>
  630. </tr>
  631. <tr>
  632. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
  633. <td width="70%">{$address}</td>
  634. </tr>
  635. <tr>
  636. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
  637. <td width="70%">{$mobile}</td>
  638. </tr>
  639. <tr>
  640. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
  641. <td width="70%">{$orderSn}</td>
  642. </tr>
  643. <tr>
  644. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
  645. <td width="70%">{$orderAt}</td>
  646. </tr>
  647. <tr>
  648. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
  649. <td class="bg"></td>
  650. </tr>
  651. </table>
  652. ORDER;
  653. $l['a_meta_charset'] = 'UTF-8';
  654. $l['a_meta_dir'] = 'ltr';
  655. $l['a_meta_language'] = 'zh';
  656. $l['w_page'] = '页面';
  657. $orderAmount = Tool::formatAmount($orderAmount);
  658. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  659. $context = <<<ORDER
  660. <!doctype html>
  661. <html lang="en">
  662. <head>
  663. <meta charset="UTF-8" />
  664. <title>Order detail</title>
  665. <style>
  666. table {
  667. border-collapse: collapse;
  668. }
  669. table td, table th {
  670. border: 1px solid #ccc;
  671. padding: 5px 5px;
  672. border-collapse: collapse;
  673. }
  674. /*td {*/
  675. /* padding: 120px;*/
  676. /*}*/
  677. .bg {
  678. background-color: #ccc;
  679. }
  680. </style>
  681. </head>
  682. <body>
  683. <div class="content">
  684. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  685. <div>
  686. <div style="display: block; width: 100%;">
  687. {$orderBase}
  688. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  689. <tr>
  690. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  691. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  692. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  693. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  694. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  695. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  696. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  697. </tr>
  698. {$orderDetails}
  699. <tr>
  700. <td colspan="3">Total</td>
  701. <td>{$orderNums}</td>
  702. <td></td>
  703. <td style="text-align: right;">{$totalTaxAmount}</td>
  704. <td style="text-align: right;">{$orderAmount}</td>
  705. </tr>
  706. </table>
  707. </div>
  708. <div style="width: 100%; margin-top: 50px; height: 30px;">
  709. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  710. <tr style="border: none;">
  711. <td width="70%" style="border: none;"></td>
  712. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  713. </tr>
  714. <tr style="border: none;">
  715. <td width="70%" style="border: none;"></td>
  716. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  717. </tr>
  718. </table>
  719. </div>
  720. </div>
  721. </div>
  722. </body>
  723. </html>
  724. ORDER;
  725. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  726. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  727. // 设置打印模式
  728. $pdf->SetCreator(PDF_CREATOR);
  729. $pdf->SetAuthor('DaZe');
  730. $pdf->SetTitle($orderSn);
  731. $pdf->SetSubject('TCPDF Tutorial');
  732. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  733. // 是否显示页眉
  734. $pdf->setPrintHeader(false);
  735. // 设置页眉字体
  736. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  737. // 页眉距离顶部的距离
  738. $pdf->SetHeaderMargin('5');
  739. // 是否显示页脚
  740. $pdf->setPrintFooter(false);
  741. // 设置默认等宽字体
  742. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  743. // 设置行高
  744. $pdf->setCellHeightRatio(1);
  745. // 设置左、上、右的间距
  746. $pdf->SetMargins('10', '0', '10');
  747. // 设置是否自动分页 距离底部多少距离时分页
  748. $pdf->SetAutoPageBreak(TRUE, '15');
  749. // 设置图像比例因子
  750. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  751. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  752. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  753. $pdf->setLanguageArray($l);
  754. }
  755. $pdf->setFontSubsetting(true);
  756. $pdf->AddPage();
  757. // 设置字体
  758. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  759. $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
  760. $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  761. $pdf->writeHTML($context);
  762. $pdf->Output($realFile, 'F');
  763. $this->_updateFirst($realFile, 1);
  764. }
  765. $this->complete();
  766. return true;
  767. }
  768. /**
  769. * 生成
  770. * @return bool
  771. * @throws Exception
  772. * @throws \yii\base\InvalidConfigException
  773. * @throws \yii\httpclient\Exception
  774. */
  775. public function generateDecOrderPDF() {
  776. $this->getParams();
  777. if (!$this->params) {
  778. throw new Exception('无法获取需要的参数');
  779. }
  780. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  781. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  782. $this->completed = false;
  783. $this->getExportId();
  784. $this->getUserId();
  785. $fileNameUpdated = false;
  786. // 获取列表数据及表头
  787. $this->_listModel = new $this->listModelClass();
  788. $this->_listModel->isExport = true;
  789. // 查询订单数据
  790. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  791. $orderQuery = Order::find()
  792. ->alias('O')
  793. ->where($this->params['condition'], $this->params['params'])
  794. ->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')
  795. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  796. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  797. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  798. ->orderBy('O.CREATED_AT DESC');
  799. // 订单中间表只查询待支付和支付失败的订单
  800. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  801. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  802. $orderStandardQuery = ApproachOrder::find()
  803. ->alias('O')
  804. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  805. ->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')
  806. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  807. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  808. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  809. ->orderBy('O.CREATED_AT DESC');
  810. $queryAll = $orderQuery->union($orderStandardQuery, true);
  811. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  812. $oderList = $query->all();
  813. if ($oderList) {
  814. $userId = '';
  815. $userName = '';
  816. $address = '';
  817. $mobile = '';
  818. $orderAt = '';
  819. $orderDetails = '';
  820. $orderSn = '';
  821. $orderAmount = 0; // 合计总额
  822. $orderNums = 0; // 合计总数
  823. $totalTaxAmount = 0; // 合计税额
  824. $totalAmount = 0;
  825. foreach ($oderList as $key => $value) {
  826. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  827. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  828. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  829. $userId = $value['USER_NAME'];
  830. $userName = $value['REAL_NAME'];
  831. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  832. $mobile = $value['MOBILE'];
  833. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  834. $orderSn = $value['SN'];
  835. // 总价
  836. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  837. $orderAmount += $totalAmount;
  838. $orderNums += $value['BUY_NUMS'];
  839. // 税额
  840. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  841. $totalTaxAmount += $taxAmount;
  842. $taxAmount = Tool::formatAmount($taxAmount);
  843. $totalAmount = Tool::formatAmount($totalAmount);
  844. // 订单详情
  845. $orderDetails .= <<<EOT
  846. <tr>
  847. <td>{$value['SKU_CODE']}</td>
  848. <td>{$value['GOODS_TITLE']}</td>
  849. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  850. <td>{$value['BUY_NUMS']}</td>
  851. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  852. <td style="text-align: right;">{$taxAmount}</td>
  853. <td style="text-align: right;">{$totalAmount}</td>
  854. </tr>
  855. EOT;
  856. }
  857. // 订单基本信息
  858. $orderBase = <<<ORDER
  859. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  860. <tr>
  861. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
  862. <td width="70%">{$userId}</td>
  863. </tr>
  864. <tr>
  865. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
  866. <td width="70%">{$userName}</td>
  867. </tr>
  868. <tr>
  869. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
  870. <td width="70%">{$address}</td>
  871. </tr>
  872. <tr>
  873. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
  874. <td width="70%">{$mobile}</td>
  875. </tr>
  876. <tr>
  877. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
  878. <td width="70%">{$orderSn}</td>
  879. </tr>
  880. <tr>
  881. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
  882. <td width="70%">{$orderAt}</td>
  883. </tr>
  884. <tr>
  885. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
  886. <td class="bg"></td>
  887. </tr>
  888. </table>
  889. ORDER;
  890. $l['a_meta_charset'] = 'UTF-8';
  891. $l['a_meta_dir'] = 'ltr';
  892. $l['a_meta_language'] = 'zh';
  893. $l['w_page'] = '页面';
  894. $orderAmount = Tool::formatAmount($orderAmount);
  895. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  896. $context = <<<ORDER
  897. <!doctype html>
  898. <html lang="en">
  899. <head>
  900. <meta charset="UTF-8" />
  901. <title>Order detail</title>
  902. <style>
  903. table {
  904. border-collapse: collapse;
  905. }
  906. table td, table th {
  907. border: 1px solid #ccc;
  908. padding: 5px 5px;
  909. border-collapse: collapse;
  910. }
  911. /*td {*/
  912. /* padding: 120px;*/
  913. /*}*/
  914. .bg {
  915. background-color: #ccc;
  916. }
  917. </style>
  918. </head>
  919. <body>
  920. <div class="content">
  921. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  922. <div>
  923. <div style="display: block; width: 100%;">
  924. {$orderBase}
  925. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  926. <tr>
  927. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  928. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  929. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  930. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  931. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  932. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  933. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  934. </tr>
  935. {$orderDetails}
  936. <tr>
  937. <td colspan="3">Total</td>
  938. <td>{$orderNums}</td>
  939. <td></td>
  940. <td style="text-align: right;">{$totalTaxAmount}</td>
  941. <td style="text-align: right;">{$orderAmount}</td>
  942. </tr>
  943. </table>
  944. </div>
  945. <div style="width: 100%; margin-top: 50px; height: 30px;">
  946. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  947. <tr style="border: none;">
  948. <td width="70%" style="border: none;"></td>
  949. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  950. </tr>
  951. <tr style="border: none;">
  952. <td width="70%" style="border: none;"></td>
  953. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  954. </tr>
  955. </table>
  956. </div>
  957. </div>
  958. </div>
  959. </body>
  960. </html>
  961. ORDER;
  962. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  963. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  964. // 设置打印模式
  965. $pdf->SetCreator(PDF_CREATOR);
  966. $pdf->SetAuthor('DaZe');
  967. $pdf->SetTitle($orderSn);
  968. $pdf->SetSubject('TCPDF Tutorial');
  969. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  970. // 是否显示页眉
  971. $pdf->setPrintHeader(false);
  972. // 设置页眉字体
  973. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  974. // 页眉距离顶部的距离
  975. $pdf->SetHeaderMargin('5');
  976. // 是否显示页脚
  977. $pdf->setPrintFooter(false);
  978. // 设置默认等宽字体
  979. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  980. // 设置行高
  981. $pdf->setCellHeightRatio(1);
  982. // 设置左、上、右的间距
  983. $pdf->SetMargins('10', '10', '10');
  984. // 设置是否自动分页 距离底部多少距离时分页
  985. $pdf->SetAutoPageBreak(TRUE, '15');
  986. // 设置图像比例因子
  987. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  988. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  989. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  990. $pdf->setLanguageArray($l);
  991. }
  992. $pdf->setFontSubsetting(true);
  993. $pdf->AddPage();
  994. // 设置字体
  995. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  996. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  997. $image = file_get_contents(\Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg');
  998. $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
  999. $pdf->writeHTML($context);
  1000. $pdf->Output($realFile, 'F');
  1001. $this->_updateFirst($realFile, 1);
  1002. }
  1003. $this->complete();
  1004. return true;
  1005. }
  1006. /**
  1007. * 循环写入数据
  1008. * @param $realFile
  1009. * @param $fileNameUpdated
  1010. * @param int $page
  1011. * @param int $counter
  1012. * @return array
  1013. * @throws Exception
  1014. */
  1015. private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  1016. if(method_exists($this->_listModel, 'getList')){
  1017. $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]);
  1018. } else {
  1019. throw new Exception($this->listModelClass.'的getList方法不存在');
  1020. }
  1021. return $list['list'];
  1022. }
  1023. /**
  1024. * 生成
  1025. * @return bool
  1026. * @throws Exception
  1027. * @throws \yii\base\InvalidConfigException
  1028. * @throws \yii\httpclient\Exception
  1029. */
  1030. public function generateBaOrderExcel() {
  1031. $this->getParams();
  1032. if (!$this->params) {
  1033. throw new Exception('无法获取需要的参数');
  1034. }
  1035. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  1036. $path = __DS__ . $path;
  1037. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  1038. $this->completed = false;
  1039. $this->getExportId();
  1040. $this->getUserId();
  1041. $this->_fp = fopen($realFile, 'w');
  1042. @exec('chown -R www:www /'.$realFile);
  1043. @exec('chmod -R 777 /'.$realFile);
  1044. // 获取列表数据及表头
  1045. $this->_listModel = new $this->listModelClass();
  1046. $this->_listModel->isExport = true;
  1047. if(method_exists($this->_listModel, 'getExportHeaders')){
  1048. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  1049. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
  1050. }
  1051. $headers = $this->_listModel->getExportHeaders($this->userId);
  1052. fputcsv($this->_fp, $headers);
  1053. unset($headers);
  1054. $this->_updateFirst($realFile, 1);
  1055. } else {
  1056. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  1057. }
  1058. $this->_loopWriteDataBaOrder();
  1059. $this->complete();
  1060. return true;
  1061. }
  1062. /**
  1063. * 循环写入数据
  1064. */
  1065. private function _loopWriteDataBaOrder()
  1066. {
  1067. $orderQuery = BaOrder::find()
  1068. ->alias('O')
  1069. ->where($this->params['condition'], $this->params['params'])
  1070. ->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')
  1071. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1072. ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1073. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1074. ->orderBy('O.CREATED_AT DESC');
  1075. // 订单中间表只查询待支付和支付失败的订单
  1076. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  1077. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  1078. $orderStandardQuery = BaApproachOrder::find()
  1079. ->alias('O')
  1080. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  1081. ->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')
  1082. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1083. ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1084. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1085. ->orderBy('O.CREATED_AT DESC');
  1086. $queryAll = $orderQuery->union($orderStandardQuery, true);
  1087. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  1088. $lists = $query->all();
  1089. if(!empty($lists)){
  1090. $regionConfig = Cache::getRegionConfig();
  1091. foreach($lists as $columnData) {
  1092. $CREATE_USER_ID = Info::getBaUserIdByUserName($columnData['CREATE_USER']);
  1093. $createUserName = Info::getBaUserRealNameByUserId($CREATE_USER_ID);
  1094. $decUserName = Info::getBaUserNameByUserId($columnData['DEC_ID']);
  1095. $columnAccept = [
  1096. 'USER_NAME' => $columnData['USER_NAME'],
  1097. 'DEC_USER_NAME' => $decUserName,
  1098. 'CREATE_USER' => $columnData['CREATE_USER'],
  1099. 'CREATE_USER_NAME' => $createUserName,
  1100. 'SN' => $columnData['SN'],
  1101. 'STATUS' => \Yii::$app->params['orderStatus'][$columnData['STATUS']]['label'] ?? '',
  1102. 'SKU_CODE' => $columnData['SKU_CODE'],
  1103. 'GOODS_TITLE' => $columnData['GOODS_TITLE'],
  1104. 'BUY_NUMS' => $columnData['BUY_NUMS'],
  1105. 'CONSIGNEE' => $columnData['CONSIGNEE'],
  1106. 'MOBILE' => "\t{$columnData['MOBILE']}",
  1107. 'TEL' => "\t{$columnData['TEL']}",
  1108. 'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
  1109. 'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
  1110. 'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
  1111. 'ADDRESS' => $columnData['ADDRESS'],
  1112. 'PERIOD_NUM' => $columnData['PERIOD_NUM'],
  1113. 'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Reselling': 'Points'),
  1114. 'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
  1115. 'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
  1116. 'PAY_AT' => $columnData['PAY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['PAY_AT']) : '',
  1117. 'DELIVERY_AT' => $columnData['DELIVERY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']) : '',
  1118. 'REAL_PRICE' => $columnData['REAL_PRICE'] ?? 0,
  1119. 'REAL_PV' => $columnData['REAL_PV'] ?? 0,
  1120. 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'] ?? 0,
  1121. 'TAX_RATE' => $columnData['TAX_RATE'],
  1122. 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
  1123. 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
  1124. 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
  1125. 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
  1126. 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
  1127. 'DELIVERY_STATUS_NAME' => \Yii::$app->params['deliveryStatus'][$columnData['DELIVERY_STATUS']]['label'] ?? '',
  1128. ];
  1129. fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
  1130. unset($percent, $columnData, $columnAccept);
  1131. }
  1132. unset($list);
  1133. }
  1134. unset($list);
  1135. return 'finish';
  1136. }
  1137. }