BaseExport.php 67 KB

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