BaseExport.php 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  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\Currency;
  20. use common\models\Export;
  21. use common\models\Order;
  22. use common\models\OrderGoods;
  23. use common\models\Region;
  24. use common\models\ShopGoods;
  25. use common\models\User;
  26. use Yii;
  27. use yii\base\Exception;
  28. use yii\base\InvalidConfigException;
  29. use yii\base\StaticInstanceTrait;
  30. use yii\base\Component;
  31. use yii\db\Query;
  32. class BaseExport extends Component {
  33. use StaticInstanceTrait;
  34. public $moduleId;
  35. /**
  36. * @var string the model class name. This property must be set.
  37. */
  38. public $modelClass;
  39. /**
  40. * @var
  41. */
  42. public $listModelClass;
  43. /**
  44. * @var int
  45. */
  46. public $pageSize = 100;
  47. /**
  48. * @var int
  49. */
  50. public $totalCount = 0;
  51. /**
  52. * @var int
  53. */
  54. public $offset = 0;
  55. /**
  56. * @var int
  57. */
  58. public $limit = 100;
  59. /**
  60. * csv文件名称
  61. * @var null
  62. */
  63. public $fileName = null;
  64. /**
  65. * 保存的基本路径
  66. * @var null
  67. */
  68. public $saveBasePath = null;
  69. /**
  70. * 保存路径
  71. * @var null
  72. */
  73. public $savePath = null;
  74. /**
  75. * 正在导出的id
  76. * 来源于exporting_file表
  77. * @var null
  78. */
  79. public $exportId = null;
  80. /**
  81. * 操作人的id
  82. * @var null
  83. */
  84. public $userId = null;
  85. /**
  86. * 任务id
  87. * @var null
  88. */
  89. public $taskId = null;
  90. /**
  91. * 是否完成
  92. * @var bool
  93. */
  94. public $completed = false;
  95. /**
  96. * @var array
  97. */
  98. public $params = [];
  99. /**
  100. * 文件句柄
  101. * @var null
  102. */
  103. private $_fp = null;
  104. /**
  105. * 是否上传远程
  106. * @var bool
  107. */
  108. public $isRemote = true;
  109. /**
  110. * @var DataList
  111. */
  112. private $_listModel;
  113. public static function factory($taskId) {
  114. return new self([
  115. 'taskId' => $taskId
  116. ]
  117. );
  118. }
  119. /**
  120. *
  121. */
  122. public function init() {
  123. parent::init();
  124. $this->isRemote = \Yii::$app->params['isRemoteUpload'];
  125. }
  126. /**
  127. * 生成复杂的路径
  128. * @return string
  129. */
  130. public function pathCreator(...$params) {
  131. $hash = md5(implode('_', $params));
  132. $first = substr($hash, 0, 3);
  133. $second = substr($hash, 3, 2);
  134. $dir = $first . __DS__ . $second . __DS__;
  135. return $dir;
  136. }
  137. /**
  138. * 获取文件名
  139. * @return string|null
  140. * @throws \Exception
  141. */
  142. public function getFileName($ext = '.csv') {
  143. $this->fileName = date('YmdHis', Date::nowTime()) . random_int(1000, 9999) . $ext;
  144. return $this->fileName;
  145. }
  146. /**
  147. * 获取保存的路径
  148. * @return array|null
  149. */
  150. public function getSavePath() {
  151. $this->savePath = $this->pathCreator(date('Ymd', Date::nowTime()));
  152. return trim((string)$this->savePath, __DS__);
  153. }
  154. /**
  155. * @return bool|string|null
  156. */
  157. public function getSaveBasePath() {
  158. $this->saveBasePath = Yii::getAlias('@backendApi') . __DS__ . 'web' . __DS__ . 'upload' . __DS__ . (isset(\Yii::$app->params['excelLocalDir']) ? \Yii::$app->params['excelLocalDir'] : '');
  159. return trim((string)$this->saveBasePath, __DS__);
  160. }
  161. /**
  162. * 创建目录(递归创建)
  163. *
  164. * @param $dir
  165. * @return string|false
  166. */
  167. public function mkdir($dir) {
  168. if (!is_dir($dir)) {
  169. $this->mkdir(dirname($dir));
  170. if (!mkdir($dir, 0777))
  171. return false;
  172. @exec('chown -R www:www /'.$dir);
  173. @exec('chmod -R 777 /'.$dir);
  174. }
  175. return $dir;
  176. }
  177. /**
  178. * @return array|mixed
  179. */
  180. public function getParams() {
  181. $this->params = CacheHelper::getAsyncParams($this->taskId);
  182. // 设置语言
  183. Yii::$app->language = $this->params['language'] ?? 'en-US';
  184. Yii::$app->sourceLanguage = Yii::$app->language == 'zh-CN' ? 'en-US' : 'zh-CN';
  185. return $this->params;
  186. }
  187. /**
  188. * @return mixed|null
  189. */
  190. public function getUserId() {
  191. $this->userId = isset($this->params['userId']) ? $this->params['userId'] : null;
  192. return $this->userId;
  193. }
  194. /**
  195. * @return |null
  196. */
  197. public function getExportId() {
  198. $this->exportId = isset($this->params['exportId']) ? $this->params['exportId'] : null;
  199. return $this->userId;
  200. }
  201. /**
  202. * 生成
  203. * @return bool
  204. * @throws Exception
  205. * @throws InvalidConfigException
  206. * @throws \yii\httpclient\Exception
  207. */
  208. public function generate() {
  209. $this->getParams();
  210. if (!$this->params) {
  211. throw new Exception('无法获取需要的参数');
  212. }
  213. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  214. $path = __DS__ . $path;
  215. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  216. $this->completed = false;
  217. $this->getExportId();
  218. $this->getUserId();
  219. $fileNameUpdated = false;
  220. $this->_fp = fopen($realFile, 'w');
  221. @exec('chown -R www:www /'.$realFile);
  222. @exec('chmod -R 777 /'.$realFile);
  223. // 获取列表数据及表头
  224. $this->_listModel = new $this->listModelClass();
  225. $this->_listModel->isExport = true;
  226. if(method_exists($this->_listModel, 'getExportHeaders')){
  227. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  228. $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]);
  229. }
  230. $headers = $this->_listModel->getExportHeaders($this->userId);
  231. fputcsv($this->_fp, $headers);
  232. unset($headers);
  233. $this->_updateFirst($realFile, 1);
  234. } else {
  235. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  236. }
  237. $this->_loopWriteData($realFile, $fileNameUpdated);
  238. $this->complete();
  239. return true;
  240. }
  241. /**
  242. * 循环写入数据
  243. * @param $realFile
  244. * @param $fileNameUpdated
  245. * @param int $page
  246. * @param int $counter
  247. * @return string
  248. * @throws Exception
  249. */
  250. private function _loopWriteData($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  251. if(method_exists($this->_listModel, 'getList')){
  252. $list = $this->_listModel->getList(['condition'=>$this->params['condition'], 'params'=> $this->params['params'] ?? [], 'others'=> $this->params['others'] ?? [], 'page'=>$page, 'pageSize'=>$this->pageSize, 'userId'=>$this->userId]);
  253. } else {
  254. throw new Exception($this->listModelClass.'的getList方法不存在');
  255. }
  256. if($page >= $list['totalPages']){
  257. return 'finish';
  258. }
  259. if(!empty($list['list'])){
  260. foreach($list['list'] as $columnData){
  261. fputcsv($this->_fp, Tool::arrTextConvert($columnData));
  262. $counter++;
  263. if ($list['totalCount'] < $counter) {
  264. // $counter = $list['totalCount'];
  265. return 'finish';
  266. }
  267. $percent = intval(($counter / $list['totalCount']) * 100);
  268. $this->_updatePercent($percent);
  269. // if (!$fileNameUpdated) {
  270. // $this->_updateFirst($realFile, $percent);
  271. // } else {
  272. // $this->_updatePercent($percent);
  273. // }
  274. // $fileNameUpdated = true;
  275. unset($percent, $columnData);
  276. }
  277. $page++;
  278. unset($list);
  279. return $this->_loopWriteData($realFile, $fileNameUpdated, $page, $counter);
  280. }
  281. unset($list);
  282. return 'finish';
  283. }
  284. /**
  285. * 循环写入数据
  286. */
  287. private function _loopWriteDataOrder()
  288. {
  289. $orderQuery = Order::find()
  290. ->alias('O')
  291. ->where($this->params['condition'], $this->params['params'])
  292. ->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')
  293. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  294. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  295. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  296. ->orderBy('O.CREATED_AT DESC');
  297. // 订单中间表只查询待支付和支付失败的订单
  298. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  299. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  300. $orderStandardQuery = ApproachOrder::find()
  301. ->alias('O')
  302. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  303. ->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')
  304. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  305. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  306. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  307. ->orderBy('O.CREATED_AT DESC');
  308. $queryAll = $orderQuery->union($orderStandardQuery, true);
  309. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  310. $lists = $query->all();
  311. if(!empty($lists)){
  312. $regionConfig = Cache::getRegionConfig();
  313. foreach($lists as $columnData) {
  314. $CREATE_USER_ID = Info::getUserIdByUserName($columnData['CREATE_USER']);
  315. $createUserName = Info::getUserRealNameByUserId($CREATE_USER_ID);
  316. $columnAccept = [
  317. 'USER_NAME' => $columnData['USER_NAME'],
  318. 'DEC_USER_NAME' => $columnData['DEC_USER_ID'],
  319. 'CREATE_USER' => $columnData['CREATE_USER'],
  320. 'CREATE_USER_NAME' => $createUserName,
  321. 'SN' => $columnData['SN'],
  322. 'STATUS' => Tool::paramConvert(\Yii::$app->params['orderStatus'])[$columnData['STATUS']]['label'] ?? '',
  323. 'SKU_CODE' => $columnData['SKU_CODE'],
  324. 'GOODS_TITLE' => Tool::mbSignConvert($columnData['GOODS_TITLE']) ,
  325. 'CONSIGNEE' => $columnData['CONSIGNEE'],
  326. 'MOBILE' => "\t{$columnData['MOBILE']}",
  327. 'TEL' => "\t{$columnData['TEL']}",
  328. 'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
  329. 'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
  330. 'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
  331. 'ADDRESS' => $columnData['ADDRESS'],
  332. 'PERIOD_NUM' => $columnData['PERIOD_NUM'],
  333. 'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Repeat Purchase': 'Points'),
  334. // 'WAREHOUSE' => $columnData['WAREHOUSE'],
  335. 'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
  336. 'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
  337. 'PAY_AT' => $columnData['PAY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['PAY_AT']) : '',
  338. 'DELIVERY_AT' => $columnData['DELIVERY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']) : '',
  339. 'BUY_NUMS' => $columnData['BUY_NUMS'],
  340. 'REAL_PRICE' => $columnData['REAL_PRICE'],
  341. 'TOTAL_PRICE' => $columnData['REAL_PRICE'] * $columnData['BUY_NUMS'],
  342. 'REAL_PV' => $columnData['REAL_PV'] * $columnData['BUY_NUMS'],
  343. 'STANDARD_PRICE' => $columnData['STANDARD_PRICE'] * $columnData['BUY_NUMS'],
  344. 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'],
  345. 'TAX_RATE' => $columnData['TAX_RATE'],
  346. 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
  347. 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
  348. 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
  349. 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
  350. 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
  351. 'DELIVERY_STATUS_NAME' => Tool::paramConvert(\Yii::$app->params['deliveryStatus'])[$columnData['DELIVERY_STATUS']]['label'] ?? '',
  352. 'IS_AUTO' => $columnData['IS_AUTO'] == 1 ? 'Yes' : 'No',
  353. ];
  354. fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
  355. unset($percent, $columnData, $columnAccept);
  356. }
  357. unset($list);
  358. }
  359. unset($list);
  360. return 'finish';
  361. }
  362. /**
  363. * 完成
  364. * @return bool
  365. * @throws Exception
  366. * @throws InvalidConfigException
  367. * @throws \yii\httpclient\Exception
  368. */
  369. public function complete() {
  370. $this->_updatePercent(100);
  371. if ($this->completed) {
  372. return true;
  373. }
  374. if ($this->_fp) {
  375. fclose($this->_fp);
  376. }
  377. // 把导出的文件上传至静态文件服务器
  378. if ($this->isRemote) {
  379. $realFile = $this->getSaveBasePath() . __DS__ . $this->getSavePath() . __DS__ . $this->getFileName();
  380. $remoteUploadApi = RemoteUploadApi::instance();
  381. if ($uploadResult = $remoteUploadApi->upload($realFile)) {
  382. Export::updateAll(['REMOTE_URL' => $uploadResult['url'], 'IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  383. } else {
  384. $this->_errorHandle();
  385. throw new Exception('文件远程上传失败');
  386. }
  387. // 删除本地临时文件
  388. unlink($realFile);
  389. } else {
  390. Export::updateAll(['IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
  391. }
  392. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin(100, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  393. CacheHelper::deleteAsyncParams($this->taskId);
  394. $this->completed = true;
  395. }
  396. /**
  397. * @param $message
  398. */
  399. private function _errorNotice($message) {
  400. Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($this->userId, $message, false);
  401. }
  402. /**
  403. * 首次更新
  404. * @param $exportId
  405. * @param $realName
  406. */
  407. private function _updateFirst($realName, $percent) {
  408. $fileName = str_replace($this->getSaveBasePath() . __DS__, '', $realName);
  409. Export::updateAll([
  410. 'FILE_NAME' => str_replace(__DS__, '/', $fileName),
  411. 'UPDATED_AT' => Date::nowTime(),
  412. 'EXPORT_PERCENT' => $percent,
  413. ], 'ID=:ID', [':ID' => $this->exportId]);
  414. }
  415. /**
  416. * 更新百分比
  417. * @param $exportId
  418. * @param $percent
  419. */
  420. private function _updatePercent($percent) {
  421. // 把数据写入数据库中
  422. Export::updateAll(['EXPORT_PERCENT' => $percent], 'ID=:ID', [':ID' => $this->exportId]);
  423. \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
  424. }
  425. /**
  426. * 发生错误处理
  427. * @param $exportId
  428. */
  429. private function _errorHandle() {
  430. Export::updateAll(['IS_EXPORTING' => 0], 'ID=:ID', [':ID' => $this->exportId]);
  431. }
  432. /**
  433. * 导出逻辑
  434. * @param $filter
  435. * @param $listName
  436. * @param null $consoleRouter
  437. * @throws Exception
  438. */
  439. public function exportHandle($filter, $listName, $consoleRouter = null){
  440. $params = [
  441. 'moduleId' => $this->moduleId,
  442. 'listName' => $listName,
  443. 'action' => $consoleRouter ? $consoleRouter : Yii::$app->controller->id.'/'.Yii::$app->controller->action->id, // 这里这么写,是因为调用的异步路由和同步的控制器和方法是一样的,所以,只要不传默认调和同步一样的异步方法
  444. 'userId' => Yii::$app->user->id,
  445. ];
  446. $this->webToAsync($params,$filter);
  447. }
  448. /**
  449. * 页面到异步的请求
  450. * @param $params
  451. * @param array $extend
  452. * @return bool
  453. * @throws Exception
  454. */
  455. public function webToAsync($params, $extend = []) {
  456. $default = [
  457. 'moduleId' => null,
  458. 'listName' => null,
  459. 'remark' => null,
  460. 'action' => null,
  461. 'userId' => null,
  462. ];
  463. $params = Tool::deepParse($params, $default);
  464. if (!$params['moduleId'] || !$params['listName'] || !$params['action']) {
  465. throw new Exception('请设置moduleId,listName和action');
  466. }
  467. // 把文件对应的相关资料存入数据库中
  468. $export = new Export();
  469. $export->EXPORT_NAME = $params['listName'] . '_' . date('Exp_y-m-d H:i:s', Date::nowTime());
  470. $export->MODULE_NAME = $params['moduleId'];
  471. $export->REMARK = $params['remark'];
  472. $export->IS_EXPORTING = 1;
  473. $export->ADMIN_ID = \Yii::$app->user->id;
  474. $export->STARTED_AT = Date::nowTime();
  475. $export->CREATED_AT = Date::nowTime();
  476. $export->EXPORT_PERCENT = 0;
  477. $export->ENDED_AT = 0;
  478. $export->UPDATED_AT = 0;
  479. if (!$export->save()) {
  480. throw new Exception(Form::formatErrorsForApi($export->getErrors()));
  481. }
  482. $extend = array_merge($extend, [
  483. 'exportId' => $export->ID,
  484. 'userId' => $params['userId'],
  485. 'language' => Yii::$app->language,
  486. ]);
  487. // 异步处理添加任务
  488. $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle($params['action'], $extend);
  489. if($taskKey === false){
  490. // 删除刚刚添加的导出数据
  491. Export::deleteAll(['ID'=>$export->ID]);
  492. throw new Exception('导出失败,请求异步处理服务器失败');
  493. }
  494. return $taskKey;
  495. }
  496. /**
  497. * 生成
  498. * @return bool
  499. * @throws Exception
  500. * @throws InvalidConfigException
  501. * @throws \yii\httpclient\Exception
  502. */
  503. public function generateOrderExcel() {
  504. $this->getParams();
  505. if (!$this->params) {
  506. throw new Exception('无法获取需要的参数');
  507. }
  508. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  509. $path = __DS__ . $path;
  510. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  511. $this->completed = false;
  512. $this->getExportId();
  513. $this->getUserId();
  514. $fileNameUpdated = false;
  515. $this->_fp = fopen($realFile, 'w');
  516. @exec('chown -R www:www /'.$realFile);
  517. @exec('chmod -R 777 /'.$realFile);
  518. // 获取列表数据及表头
  519. $this->_listModel = new $this->listModelClass();
  520. $this->_listModel->isExport = true;
  521. if(method_exists($this->_listModel, 'getExportHeaders')){
  522. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  523. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
  524. }
  525. $headers = $this->_listModel->getExportHeaders($this->userId);
  526. fputcsv($this->_fp, $headers);
  527. unset($headers);
  528. $this->_updateFirst($realFile, 1);
  529. } else {
  530. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  531. }
  532. $this->_loopWriteDataOrder();
  533. $this->complete();
  534. return true;
  535. }
  536. /**
  537. * 生成
  538. * @return bool
  539. * @throws Exception
  540. * @throws InvalidConfigException
  541. * @throws \yii\httpclient\Exception
  542. */
  543. public function generateOrderPDF() {
  544. $this->getParams();
  545. if (!$this->params) {
  546. throw new Exception('无法获取需要的参数');
  547. }
  548. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  549. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName('.pdf');
  550. $this->completed = false;
  551. $this->getExportId();
  552. $this->getUserId();
  553. $fileNameUpdated = false;
  554. // 获取列表数据及表头
  555. $this->_listModel = new $this->listModelClass();
  556. $this->_listModel->isExport = true;
  557. // 查询订单数据
  558. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  559. $orderQuery = Order::find()
  560. ->alias('O')
  561. ->where($this->params['condition'], $this->params['params'])
  562. ->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')
  563. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  564. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  565. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  566. ->orderBy('O.CREATED_AT DESC');
  567. // 订单中间表只查询待支付和支付失败的订单
  568. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  569. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  570. $orderStandardQuery = ApproachOrder::find()
  571. ->alias('O')
  572. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  573. ->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')
  574. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  575. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  576. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  577. ->orderBy('O.CREATED_AT DESC');
  578. $queryAll = $orderQuery->union($orderStandardQuery, true);
  579. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  580. $oderList = $query->all();
  581. if ($oderList) {
  582. $userId = '';
  583. $userName = '';
  584. $address = '';
  585. $mobile = '';
  586. $orderAt = '';
  587. $orderDetails = '';
  588. $orderSn = '';
  589. $orderAmount = 0; // 合计总额
  590. $orderNums = 0; // 合计总数
  591. $totalTaxAmount = 0; // 合计税额
  592. $totalAmount = 0;
  593. foreach ($oderList as $key => $value) {
  594. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  595. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  596. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  597. $userId = $value['USER_NAME'];
  598. $userName = $value['REAL_NAME'];
  599. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  600. $mobile = $value['MOBILE'];
  601. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  602. $orderSn = $value['SN'];
  603. // 总价
  604. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  605. $orderAmount += $totalAmount;
  606. $orderNums += $value['BUY_NUMS'];
  607. // 税额
  608. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  609. $totalTaxAmount += $taxAmount;
  610. $taxAmount = Tool::formatAmount($taxAmount);
  611. $totalAmount = Tool::formatAmount($totalAmount);
  612. // 订单详情
  613. $orderDetails .= <<<EOT
  614. <tr>
  615. <td>{$value['SKU_CODE']}</td>
  616. <td>{$value['GOODS_TITLE']}</td>
  617. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  618. <td>{$value['BUY_NUMS']}</td>
  619. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  620. <td style="text-align: right;">{$taxAmount}</td>
  621. <td style="text-align: right;">{$totalAmount}</td>
  622. </tr>
  623. EOT;
  624. }
  625. $memberCode = Yii::t('app', 'memberCode');
  626. $memberName = Yii::t('app', 'memberName');
  627. $memberAddress = Yii::t('app', 'memberAddress');
  628. $memberPhone = Yii::t('app', 'memberPhone');
  629. $orderCode = Yii::t('app', 'orderCode');
  630. $orderDetail = Yii::t('app', 'orderDetail');
  631. $productCode = Yii::t('app', 'productCode');
  632. $productName = Yii::t('app', 'productName');
  633. $productPrice = Yii::t('app', 'productPrice');
  634. $quantity = Yii::t('app', 'qty');
  635. $taxRate = Yii::t('app', 'taxRate');
  636. $totalTax = Yii::t('app', 'totalTax');
  637. $totalAmount = Yii::t('app', 'totalAmount');
  638. $total = Yii::t('app', 'total');
  639. $signature = Yii::t('app', 'signature');
  640. $date = Yii::t('app', 'date');
  641. $createAt = Yii::t('app', 'createAt');
  642. // 订单基本信息
  643. $orderBase = <<<ORDER
  644. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  645. <tr>
  646. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberCode}</td>
  647. <td width="70%">{$userId}</td>
  648. </tr>
  649. <tr>
  650. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberName}</td>
  651. <td width="70%">{$userName}</td>
  652. </tr>
  653. <tr>
  654. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberAddress}</td>
  655. <td width="70%">{$address}</td>
  656. </tr>
  657. <tr>
  658. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberPhone}</td>
  659. <td width="70%">{$mobile}</td>
  660. </tr>
  661. <tr>
  662. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$orderCode}</td>
  663. <td width="70%">{$orderSn}</td>
  664. </tr>
  665. <tr>
  666. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$createAt}</td>
  667. <td width="70%">{$orderAt}</td>
  668. </tr>
  669. <tr>
  670. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">{$orderDetail}</td>
  671. <td class="bg"></td>
  672. </tr>
  673. </table>
  674. ORDER;
  675. $l['a_meta_charset'] = 'UTF-8';
  676. $l['a_meta_dir'] = 'ltr';
  677. $l['a_meta_language'] = 'zh';
  678. $l['w_page'] = '页面';
  679. $orderAmount = Tool::formatAmount($orderAmount);
  680. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  681. $context = <<<ORDER
  682. <!doctype html>
  683. <html lang="en">
  684. <head>
  685. <meta charset="UTF-8" />
  686. <title>{$orderDetail}</title>
  687. <style>
  688. table {
  689. border-collapse: collapse;
  690. }
  691. table td, table th {
  692. border: 1px solid #ccc;
  693. /*padding: 5px 5px;*/
  694. border-collapse: collapse;
  695. }
  696. /*td {*/
  697. /* padding: 120px;*/
  698. /*}*/
  699. .bg {
  700. background-color: #ccc;
  701. }
  702. </style>
  703. </head>
  704. <body>
  705. <div class="content">
  706. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>{$orderDetail}</b><br></p>
  707. <div>
  708. <div style="display: block; width: 100%;">
  709. {$orderBase}
  710. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  711. <tr>
  712. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productCode}</th>
  713. <th width="20%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productName}</th>
  714. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productPrice}</th>
  715. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">{$quantity}</th>
  716. <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">{$taxRate}</th>
  717. <th width="13%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalTax}</th>
  718. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalAmount}</th>
  719. </tr>
  720. {$orderDetails}
  721. <tr>
  722. <td colspan="3">{$total}</td>
  723. <td style="text-align: right;">{$orderNums}</td>
  724. <td></td>
  725. <td style="text-align: right;">{$totalTaxAmount}</td>
  726. <td style="text-align: right;">{$orderAmount}</td>
  727. </tr>
  728. </table>
  729. </div>
  730. <div style="width: 100%; margin-top: 50px; height: 30px;">
  731. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  732. <tr style="border: none;">
  733. <td width="70%" style="border: none;"></td>
  734. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$signature}:</td>
  735. </tr>
  736. <tr style="border: none;">
  737. <td width="70%" style="border: none;"></td>
  738. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$date}:</td>
  739. </tr>
  740. </table>
  741. </div>
  742. </div>
  743. </div>
  744. </body>
  745. </html>
  746. ORDER;
  747. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  748. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  749. // 设置打印模式
  750. $pdf->SetCreator(PDF_CREATOR);
  751. $pdf->SetAuthor('DaZe');
  752. $pdf->SetTitle($orderSn);
  753. $pdf->SetSubject('TCPDF Tutorial');
  754. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  755. // 是否显示页眉
  756. $pdf->setPrintHeader(false);
  757. // 设置页眉字体
  758. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  759. // 页眉距离顶部的距离
  760. $pdf->SetHeaderMargin('5');
  761. // 是否显示页脚
  762. $pdf->setPrintFooter(false);
  763. // 设置默认等宽字体
  764. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  765. // 设置行高
  766. $pdf->setCellHeightRatio(1);
  767. // 设置左、上、右的间距
  768. $pdf->SetMargins('15', '15', '15');
  769. // 设置是否自动分页 距离底部多少距离时分页
  770. $pdf->SetAutoPageBreak(TRUE, '15');
  771. // 设置图像比例因子
  772. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  773. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  774. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  775. $pdf->setLanguageArray($l);
  776. }
  777. $pdf->setFontSubsetting(true);
  778. $pdf->AddPage();
  779. // 设置字体
  780. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  781. // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
  782. // if (!file_exists($image_file)) {
  783. // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
  784. // }
  785. $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  786. $image = file_get_contents($image_file);
  787. $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  788. $pdf->writeHTML($context);
  789. $result = $pdf->Output($realFile, 'F');
  790. LoggerTool::debug(['result' => $result]);
  791. $this->_updateFirst($realFile, 1);
  792. }
  793. $this->complete();
  794. return true;
  795. }
  796. /**
  797. * 生成
  798. * @return bool
  799. * @throws Exception
  800. * @throws InvalidConfigException
  801. * @throws \yii\httpclient\Exception
  802. */
  803. public function generateDecOrderPDF() {
  804. $this->getParams();
  805. if (!$this->params) {
  806. throw new Exception('无法获取需要的参数');
  807. }
  808. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  809. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  810. $this->completed = false;
  811. $this->getExportId();
  812. $this->getUserId();
  813. $fileNameUpdated = false;
  814. // 获取列表数据及表头
  815. $this->_listModel = new $this->listModelClass();
  816. $this->_listModel->isExport = true;
  817. // 查询订单数据
  818. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  819. $orderQuery = Order::find()
  820. ->alias('O')
  821. ->where($this->params['condition'], $this->params['params'])
  822. ->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')
  823. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  824. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  825. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  826. ->orderBy('O.CREATED_AT DESC');
  827. // 订单中间表只查询待支付和支付失败的订单
  828. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  829. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  830. $orderStandardQuery = ApproachOrder::find()
  831. ->alias('O')
  832. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  833. ->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')
  834. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  835. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  836. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  837. ->orderBy('O.CREATED_AT DESC');
  838. $queryAll = $orderQuery->union($orderStandardQuery, true);
  839. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  840. $oderList = $query->all();
  841. if ($oderList) {
  842. $userId = '';
  843. $userName = '';
  844. $address = '';
  845. $mobile = '';
  846. $orderAt = '';
  847. $orderDetails = '';
  848. $orderSn = '';
  849. $orderAmount = 0; // 合计总额
  850. $orderNums = 0; // 合计总数
  851. $totalTaxAmount = 0; // 合计税额
  852. $totalAmount = 0;
  853. foreach ($oderList as $key => $value) {
  854. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  855. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  856. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  857. $userId = $value['USER_NAME'];
  858. $userName = $value['REAL_NAME'];
  859. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  860. $mobile = $value['MOBILE'];
  861. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  862. $orderSn = $value['SN'];
  863. // 总价
  864. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  865. $orderAmount += $totalAmount;
  866. $orderNums += $value['BUY_NUMS'];
  867. // 税额
  868. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  869. $totalTaxAmount += $taxAmount;
  870. $taxAmount = Tool::formatAmount($taxAmount);
  871. $totalAmount = Tool::formatAmount($totalAmount);
  872. // 订单详情
  873. $orderDetails .= <<<EOT
  874. <tr>
  875. <td>{$value['SKU_CODE']}</td>
  876. <td>{$value['GOODS_TITLE']}</td>
  877. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  878. <td>{$value['BUY_NUMS']}</td>
  879. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  880. <td style="text-align: right;">{$taxAmount}</td>
  881. <td style="text-align: right;">{$totalAmount}</td>
  882. </tr>
  883. EOT;
  884. }
  885. $memberCode = Yii::t('app', 'memberCode');
  886. $memberName = Yii::t('app', 'memberName');
  887. $memberAddress = Yii::t('app', 'memberAddress');
  888. $memberPhone = Yii::t('app', 'memberPhone');
  889. $orderCode = Yii::t('app', 'orderCode');
  890. $orderDetail = Yii::t('app', 'orderDetail');
  891. $productCode = Yii::t('app', 'productCode');
  892. $productName = Yii::t('app', 'productName');
  893. $productPrice = Yii::t('app', 'productPrice');
  894. $quantity = Yii::t('app', 'qty');
  895. $taxRate = Yii::t('app', 'taxRate');
  896. $totalTax = Yii::t('app', 'totalTax');
  897. $totalAmount = Yii::t('app', 'totalAmount');
  898. $total = Yii::t('app', 'total');
  899. $signature = Yii::t('app', 'signature');
  900. $date = Yii::t('app', 'date');
  901. $createAt = Yii::t('app', 'createAt');
  902. // 订单基本信息
  903. $orderBase = <<<ORDER
  904. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  905. <tr>
  906. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberCode}</td>
  907. <td width="70%">{$userId}</td>
  908. </tr>
  909. <tr>
  910. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberName}</td>
  911. <td width="70%">{$userName}</td>
  912. </tr>
  913. <tr>
  914. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberAddress}</td>
  915. <td width="70%">{$address}</td>
  916. </tr>
  917. <tr>
  918. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberPhone}</td>
  919. <td width="70%">{$mobile}</td>
  920. </tr>
  921. <tr>
  922. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$orderCode}</td>
  923. <td width="70%">{$orderSn}</td>
  924. </tr>
  925. <tr>
  926. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$createAt}</td>
  927. <td width="70%">{$orderAt}</td>
  928. </tr>
  929. <tr>
  930. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">{$orderDetail}</td>
  931. <td class="bg"></td>
  932. </tr>
  933. </table>
  934. ORDER;
  935. $l['a_meta_charset'] = 'UTF-8';
  936. $l['a_meta_dir'] = 'ltr';
  937. $l['a_meta_language'] = 'zh';
  938. $l['w_page'] = '页面';
  939. $orderAmount = sprintf('%.2f', $orderAmount);
  940. $totalTaxAmount = sprintf('%.2f', $totalTaxAmount);
  941. $context = <<<ORDER
  942. <!doctype html>
  943. <html lang="en">
  944. <head>
  945. <meta charset="UTF-8" />
  946. <title>{$orderDetail}</title>
  947. <style>
  948. table {
  949. border-collapse: collapse;
  950. }
  951. table td, table th {
  952. border: 1px solid #ccc;
  953. /*padding: 5px 5px;*/
  954. border-collapse: collapse;
  955. }
  956. /*td {*/
  957. /* padding: 120px;*/
  958. /*}*/
  959. .bg {
  960. background-color: #ccc;
  961. }
  962. </style>
  963. </head>
  964. <body>
  965. <div class="content">
  966. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>{$orderDetail}</b><br></p>
  967. <div>
  968. <div style="display: block; width: 100%;">
  969. {$orderBase}
  970. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  971. <tr>
  972. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productCode}</th>
  973. <th width="20%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productName}</th>
  974. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productPrice}</th>
  975. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">{$quantity}</th>
  976. <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">{$taxRate}</th>
  977. <th width="13%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalTax}</th>
  978. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalAmount}</th>
  979. </tr>
  980. {$orderDetails}
  981. <tr>
  982. <td colspan="3">{$total}</td>
  983. <td style="text-align: right;">{$orderNums}</td>
  984. <td></td>
  985. <td style="text-align: right;">{$totalTaxAmount}</td>
  986. <td style="text-align: right;">{$orderAmount}</td>
  987. </tr>
  988. </table>
  989. </div>
  990. <div style="width: 100%; margin-top: 50px; height: 30px;">
  991. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  992. <tr style="border: none;">
  993. <td width="70%" style="border: none;"></td>
  994. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$signature}:</td>
  995. </tr>
  996. <tr style="border: none;">
  997. <td width="70%" style="border: none;"></td>
  998. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$date}:</td>
  999. </tr>
  1000. </table>
  1001. </div>
  1002. </div>
  1003. </div>
  1004. </body>
  1005. </html>
  1006. ORDER;
  1007. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  1008. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1009. // 设置打印模式
  1010. $pdf->SetCreator(PDF_CREATOR);
  1011. $pdf->SetAuthor('DaZe');
  1012. $pdf->SetTitle($orderSn);
  1013. $pdf->SetSubject('TCPDF Tutorial');
  1014. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  1015. // 是否显示页眉
  1016. $pdf->setPrintHeader(false);
  1017. // 设置页眉字体
  1018. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  1019. // 页眉距离顶部的距离
  1020. $pdf->SetHeaderMargin('5');
  1021. // 是否显示页脚
  1022. $pdf->setPrintFooter(false);
  1023. // 设置默认等宽字体
  1024. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  1025. // 设置行高
  1026. $pdf->setCellHeightRatio(1);
  1027. // 设置左、上、右的间距
  1028. $pdf->SetMargins('10', '10', '10');
  1029. // 设置是否自动分页 距离底部多少距离时分页
  1030. $pdf->SetAutoPageBreak(TRUE, '15');
  1031. // 设置图像比例因子
  1032. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1033. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  1034. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  1035. $pdf->setLanguageArray($l);
  1036. }
  1037. $pdf->setFontSubsetting(true);
  1038. $pdf->AddPage();
  1039. // 设置字体
  1040. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  1041. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1042. // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
  1043. // if (!file_exists($image_file)) {
  1044. // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
  1045. // }
  1046. $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  1047. $image = file_get_contents($image_file);
  1048. $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
  1049. $pdf->writeHTML($context);
  1050. $pdf->Output($realFile, 'F');
  1051. $this->_updateFirst($realFile, 1);
  1052. }
  1053. $this->complete();
  1054. return true;
  1055. }
  1056. /**
  1057. * 循环写入数据
  1058. * @param $realFile
  1059. * @param $fileNameUpdated
  1060. * @param int $page
  1061. * @param int $counter
  1062. * @return array
  1063. * @throws Exception
  1064. */
  1065. private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  1066. if(method_exists($this->_listModel, 'getList')){
  1067. $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]);
  1068. } else {
  1069. throw new Exception($this->listModelClass.'的getList方法不存在');
  1070. }
  1071. return $list['list'];
  1072. }
  1073. /**
  1074. * 生成
  1075. * @return bool
  1076. * @throws Exception
  1077. * @throws InvalidConfigException
  1078. * @throws \yii\httpclient\Exception
  1079. */
  1080. public function generateBaOrderExcel() {
  1081. $this->getParams();
  1082. if (!$this->params) {
  1083. throw new Exception('无法获取需要的参数');
  1084. }
  1085. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  1086. $path = __DS__ . $path;
  1087. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  1088. $this->completed = false;
  1089. $this->getExportId();
  1090. $this->getUserId();
  1091. $this->_fp = fopen($realFile, 'w');
  1092. @exec('chown -R www:www /'.$realFile);
  1093. @exec('chmod -R 777 /'.$realFile);
  1094. // 获取列表数据及表头
  1095. $this->_listModel = new $this->listModelClass();
  1096. $this->_listModel->isExport = true;
  1097. if(method_exists($this->_listModel, 'getExportHeaders')){
  1098. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  1099. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
  1100. }
  1101. $headers = $this->_listModel->getExportHeaders($this->userId);
  1102. fputcsv($this->_fp, $headers);
  1103. unset($headers);
  1104. $this->_updateFirst($realFile, 1);
  1105. } else {
  1106. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  1107. }
  1108. $this->_loopWriteDataBaOrder();
  1109. $this->complete();
  1110. return true;
  1111. }
  1112. /**
  1113. * 循环写入数据
  1114. */
  1115. private function _loopWriteDataBaOrder()
  1116. {
  1117. $orderQuery = BaOrder::find()
  1118. ->alias('O')
  1119. ->where($this->params['condition'], $this->params['params'])
  1120. ->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')
  1121. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1122. ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1123. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1124. ->orderBy('O.CREATED_AT DESC');
  1125. // 订单中间表只查询待支付和支付失败的订单
  1126. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  1127. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  1128. $orderStandardQuery = BaApproachOrder::find()
  1129. ->alias('O')
  1130. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  1131. ->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')
  1132. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1133. ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1134. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1135. ->orderBy('O.CREATED_AT DESC');
  1136. $queryAll = $orderQuery->union($orderStandardQuery, true);
  1137. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  1138. $lists = $query->all();
  1139. if(!empty($lists)){
  1140. $regionConfig = Cache::getRegionConfig();
  1141. foreach($lists as $columnData) {
  1142. $CREATE_USER_ID = Info::getBaUserIdByUserName($columnData['CREATE_USER']);
  1143. $createUserName = Info::getBaUserRealNameByUserId($CREATE_USER_ID);
  1144. $decUserName = Info::getBaUserNameByUserId($columnData['DEC_ID']);
  1145. $columnAccept = [
  1146. 'USER_NAME' => $columnData['USER_NAME'],
  1147. 'DEC_USER_NAME' => $decUserName,
  1148. 'CREATE_USER' => $columnData['CREATE_USER'],
  1149. 'CREATE_USER_NAME' => $createUserName,
  1150. 'SN' => $columnData['SN'],
  1151. 'STATUS' => Tool::paramConvert(\Yii::$app->params['orderStatus'])[$columnData['STATUS']]['label'] ?? '',
  1152. 'SKU_CODE' => $columnData['SKU_CODE'],
  1153. 'GOODS_TITLE' => $columnData['GOODS_TITLE'],
  1154. 'BUY_NUMS' => $columnData['BUY_NUMS'],
  1155. 'CONSIGNEE' => $columnData['CONSIGNEE'],
  1156. 'MOBILE' => "\t{$columnData['MOBILE']}",
  1157. 'TEL' => "\t{$columnData['TEL']}",
  1158. 'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
  1159. 'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
  1160. 'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
  1161. 'ADDRESS' => $columnData['ADDRESS'],
  1162. 'PERIOD_NUM' => $columnData['PERIOD_NUM'],
  1163. 'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Reselling': 'Points'),
  1164. 'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
  1165. 'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
  1166. 'PAY_AT' => $columnData['PAY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['PAY_AT']) : '',
  1167. 'DELIVERY_AT' => $columnData['DELIVERY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']) : '',
  1168. 'REAL_PRICE' => $columnData['REAL_PRICE'] ?? 0,
  1169. 'REAL_PV' => $columnData['REAL_PV'] ?? 0,
  1170. 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'] ?? 0,
  1171. 'TAX_RATE' => $columnData['TAX_RATE'],
  1172. 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
  1173. 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
  1174. 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
  1175. 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
  1176. 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
  1177. 'DELIVERY_STATUS_NAME' => Tool::paramConvert(\Yii::$app->params['deliveryStatus'])[$columnData['DELIVERY_STATUS']]['label'] ?? '',
  1178. ];
  1179. fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
  1180. unset($percent, $columnData, $columnAccept);
  1181. }
  1182. unset($list);
  1183. }
  1184. unset($list);
  1185. return 'finish';
  1186. }
  1187. /**
  1188. * 生成
  1189. * @return bool
  1190. * @throws Exception
  1191. * @throws InvalidConfigException
  1192. * @throws \yii\httpclient\Exception
  1193. */
  1194. public function generateBaOrderPDF()
  1195. {
  1196. $this->getParams();
  1197. if (!$this->params) {
  1198. throw new Exception('无法获取需要的参数');
  1199. }
  1200. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  1201. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  1202. $this->completed = false;
  1203. $this->getExportId();
  1204. $this->getUserId();
  1205. $fileNameUpdated = false;
  1206. // 获取列表数据及表头
  1207. $this->_listModel = new $this->listModelClass();
  1208. $this->_listModel->isExport = true;
  1209. // 查询订单数据
  1210. $orderQuery = BaOrder::find()
  1211. ->alias('O')
  1212. ->where($this->params['condition'], $this->params['params'])
  1213. ->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')
  1214. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1215. ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1216. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1217. ->orderBy('O.CREATED_AT DESC');
  1218. // 订单中间表只查询待支付和支付失败的订单
  1219. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  1220. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  1221. $orderStandardQuery = BaApproachOrder::find()
  1222. ->alias('O')
  1223. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  1224. ->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')
  1225. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1226. ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1227. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1228. ->orderBy('O.CREATED_AT DESC');
  1229. $queryAll = $orderQuery->union($orderStandardQuery, true);
  1230. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  1231. $oderList = $query->all();
  1232. if ($oderList) {
  1233. $userId = '';
  1234. $userName = '';
  1235. $address = '';
  1236. $mobile = '';
  1237. $orderAt = '';
  1238. $orderDetails = '';
  1239. $orderSn = '';
  1240. $orderAmount = 0; // 合计总额
  1241. $orderNums = 0; // 合计总数
  1242. $totalTaxAmount = 0; // 合计税额
  1243. $totalAmount = 0;
  1244. foreach ($oderList as $key => $value) {
  1245. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  1246. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  1247. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  1248. $userId = $value['USER_NAME'];
  1249. $userName = $value['REAL_NAME'];
  1250. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  1251. $mobile = $value['MOBILE'];
  1252. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  1253. $orderSn = $value['SN'];
  1254. // 总价
  1255. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  1256. $orderAmount += $totalAmount;
  1257. $orderNums += $value['BUY_NUMS'];
  1258. // 税额
  1259. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  1260. $totalTaxAmount += $taxAmount;
  1261. $taxAmount = Tool::formatAmount($taxAmount);
  1262. $totalAmount = Tool::formatAmount($totalAmount);
  1263. // 订单详情
  1264. $orderDetails .= <<<EOT
  1265. <tr>
  1266. <td>{$value['SKU_CODE']}</td>
  1267. <td>{$value['GOODS_TITLE']}</td>
  1268. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  1269. <td>{$value['BUY_NUMS']}</td>
  1270. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  1271. <td style="text-align: right;">{$taxAmount}</td>
  1272. <td style="text-align: right;">{$totalAmount}</td>
  1273. </tr>
  1274. EOT;
  1275. }
  1276. // 订单基本信息
  1277. $orderBase = <<<ORDER
  1278. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  1279. <tr>
  1280. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
  1281. <td width="70%">{$userId}</td>
  1282. </tr>
  1283. <tr>
  1284. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
  1285. <td width="70%">{$userName}</td>
  1286. </tr>
  1287. <tr>
  1288. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
  1289. <td width="70%">{$address}</td>
  1290. </tr>
  1291. <tr>
  1292. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
  1293. <td width="70%">{$mobile}</td>
  1294. </tr>
  1295. <tr>
  1296. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
  1297. <td width="70%">{$orderSn}</td>
  1298. </tr>
  1299. <tr>
  1300. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
  1301. <td width="70%">{$orderAt}</td>
  1302. </tr>
  1303. <tr>
  1304. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
  1305. <td class="bg"></td>
  1306. </tr>
  1307. </table>
  1308. ORDER;
  1309. $l['a_meta_charset'] = 'UTF-8';
  1310. $l['a_meta_dir'] = 'ltr';
  1311. $l['a_meta_language'] = 'zh';
  1312. $l['w_page'] = '页面';
  1313. $orderAmount = Tool::formatAmount($orderAmount);
  1314. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  1315. $context = <<<ORDER
  1316. <!doctype html>
  1317. <html lang="en">
  1318. <head>
  1319. <meta charset="UTF-8" />
  1320. <title>Order detail</title>
  1321. <style>
  1322. table {
  1323. border-collapse: collapse;
  1324. }
  1325. table td, table th {
  1326. border: 1px solid #ccc;
  1327. padding: 5px 5px;
  1328. border-collapse: collapse;
  1329. }
  1330. /*td {*/
  1331. /* padding: 120px;*/
  1332. /*}*/
  1333. .bg {
  1334. background-color: #ccc;
  1335. }
  1336. </style>
  1337. </head>
  1338. <body>
  1339. <div class="content">
  1340. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  1341. <div>
  1342. <div style="display: block; width: 100%;">
  1343. {$orderBase}
  1344. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  1345. <tr>
  1346. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  1347. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  1348. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  1349. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  1350. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  1351. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  1352. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  1353. </tr>
  1354. {$orderDetails}
  1355. <tr>
  1356. <td colspan="3">Total</td>
  1357. <td>{$orderNums}</td>
  1358. <td></td>
  1359. <td style="text-align: right;">{$totalTaxAmount}</td>
  1360. <td style="text-align: right;">{$orderAmount}</td>
  1361. </tr>
  1362. </table>
  1363. </div>
  1364. <div style="width: 100%; margin-top: 50px; height: 30px;">
  1365. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  1366. <tr style="border: none;">
  1367. <td width="70%" style="border: none;"></td>
  1368. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  1369. </tr>
  1370. <tr style="border: none;">
  1371. <td width="70%" style="border: none;"></td>
  1372. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  1373. </tr>
  1374. </table>
  1375. </div>
  1376. </div>
  1377. </div>
  1378. </body>
  1379. </html>
  1380. ORDER;
  1381. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  1382. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1383. // 设置打印模式
  1384. $pdf->SetCreator(PDF_CREATOR);
  1385. $pdf->SetAuthor('DaZe');
  1386. $pdf->SetTitle($orderSn);
  1387. $pdf->SetSubject('TCPDF Tutorial');
  1388. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  1389. // 是否显示页眉
  1390. $pdf->setPrintHeader(false);
  1391. // 设置页眉字体
  1392. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  1393. // 页眉距离顶部的距离
  1394. $pdf->SetHeaderMargin('5');
  1395. // 是否显示页脚
  1396. $pdf->setPrintFooter(false);
  1397. // 设置默认等宽字体
  1398. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  1399. // 设置行高
  1400. $pdf->setCellHeightRatio(1);
  1401. // 设置左、上、右的间距
  1402. $pdf->SetMargins('10', '0', '10');
  1403. // 设置是否自动分页 距离底部多少距离时分页
  1404. $pdf->SetAutoPageBreak(TRUE, '15');
  1405. // 设置图像比例因子
  1406. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1407. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  1408. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  1409. $pdf->setLanguageArray($l);
  1410. }
  1411. $pdf->setFontSubsetting(true);
  1412. $pdf->AddPage();
  1413. // 设置字体
  1414. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  1415. // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
  1416. // if (!file_exists($image_file)) {
  1417. // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
  1418. // }
  1419. $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  1420. $image = file_get_contents($image_file);
  1421. $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  1422. $pdf->writeHTML($context);
  1423. $pdf->Output($realFile, 'F');
  1424. $this->_updateFirst($realFile, 1);
  1425. }
  1426. $this->complete();
  1427. return true;
  1428. }
  1429. /**
  1430. * 生成
  1431. * @return bool
  1432. * @throws Exception
  1433. * @throws InvalidConfigException
  1434. * @throws \yii\httpclient\Exception
  1435. */
  1436. public function actionOrderInvoiceExport() {
  1437. $this->getParams();
  1438. if (!$this->params) {
  1439. throw new Exception('无法获取需要的参数');
  1440. }
  1441. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  1442. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName('.pdf');
  1443. $this->completed = false;
  1444. $this->getExportId();
  1445. $this->getUserId();
  1446. $fileNameUpdated = false;
  1447. // 获取列表数据及表头
  1448. $this->_listModel = new $this->listModelClass();
  1449. $this->_listModel->isExport = true;
  1450. // 查询订单数据
  1451. // 使用新的查询对象,禁用查询缓存,确保获取最新数据
  1452. $query = OrderGoods::find()
  1453. ->alias('OG')
  1454. ->where($this->params['condition'], $this->params['params'])
  1455. ->select('OG.ID AS AID,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')
  1456. ->join('LEFT JOIN', ORDER::tableName() . ' AS O', 'OG.ORDER_SN=O.SN')
  1457. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1458. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1459. ->asArray()
  1460. ->noCache(); // 禁用查询缓存
  1461. // 添加详细的调试信息
  1462. $rawSql = $query->createCommand()->getRawSql();
  1463. $oderList = $query->all();
  1464. $sn = $oderList[0]['SN'];
  1465. // 同时使用原生SQL查询进行对比测试
  1466. $nativeConnection = Yii::$app->db;
  1467. $nativeQuery = "
  1468. SELECT
  1469. `OG`.`ID` AS `AID`,
  1470. `O`.*,
  1471. `U`.`REAL_NAME`,
  1472. `U`.`DEC_ID`,
  1473. `SG`.`CATEGORY_TYPE`,
  1474. `OG`.`REAL_PRICE`,
  1475. `OG`.`TAX_RATE`,
  1476. `OG`.`BUY_NUMS`,
  1477. `OG`.`SKU_CODE`,
  1478. `OG`.`GOODS_TITLE`,
  1479. `OG`.`REAL_PV`
  1480. FROM
  1481. `AR_ORDER_GOODS` `OG`
  1482. LEFT JOIN `AR_ORDER` `O` ON OG.ORDER_SN = O.SN
  1483. LEFT JOIN `AR_USER` `U` ON U.ID = O.USER_ID
  1484. LEFT JOIN `AR_SHOP_GOODS` `SG` ON SG.ID = OG.GOODS_ID
  1485. WHERE
  1486. O.IS_DELETE = 0
  1487. AND O.SN = '{$sn}'
  1488. ORDER BY
  1489. `O`.`CREATED_AT` DESC";
  1490. $nativeResults = $nativeConnection->createCommand($nativeQuery)->queryAll();
  1491. // 如果原生查询有结果但Yii查询没有,使用原生查询结果
  1492. if(count($nativeResults) > 0 && count($oderList) < count($nativeResults)) {
  1493. $oderList = $nativeResults;
  1494. }
  1495. if ($oderList) {
  1496. $userId = '';
  1497. $userName = '';
  1498. $address = '';
  1499. $mobile = $oderList[0]['MOBILE'];
  1500. $orderAt = Date::convert($oderList[0]['CREATED_AT'],'Y/m/d');
  1501. $orderDetails = '';
  1502. $orderSn = $oderList[0]['SN'];;
  1503. $orderAmount = 0; // 合计总额
  1504. $orderNums = 0; // 合计总数
  1505. $totalTaxAmount = 0; // 合计税额
  1506. $totalAmount = 0;
  1507. $paymentStatus = 'Paid'; // 支付状态
  1508. $invoiceRemark = $oderList[0]['INVOICE_REMARK'];
  1509. $paymentMethod = $oderList[0]['PAY_TYPE']; // 支付方式
  1510. $currency = Currency::findOne($oderList[0]['CURRENCY_ID'])['CODE'] ?? '';;
  1511. $invoiceNo = $oderList[0]['INVOICE_NO'];
  1512. $provinceName = $oderList[0]['PROVINCE'] ? Region::getCnName($oderList[0]['PROVINCE']) : '';
  1513. $cityName = $oderList[0]['CITY'] ? Region::getCnName($oderList[0]['CITY']) : '';
  1514. $countyName = $oderList[0]['COUNTY'] ? Region::getCnName($oderList[0]['COUNTY']) : '';
  1515. $address = $provinceName . $cityName . $countyName . $oderList[0]['ADDRESS'];
  1516. $paymentMethod = $oderList[0]['PAY_TYPE'] ?? 'Cash';
  1517. $paymentStatus = \Yii::$app->params['orderStatus'][$oderList[0]['STATUS']]['label'] ?? 'Paid';
  1518. $orderTotalBv = 0;
  1519. $orderTotalTaxAmount = 0;
  1520. $orderTotalAmount = 0;
  1521. $orderTotal = 0;
  1522. $orderTotalQuantity = count($oderList);
  1523. $no = 0;
  1524. foreach ($oderList as $key => $value) {
  1525. $no += 1;
  1526. $userId = $value['USER_NAME'];
  1527. $userName = $value['REAL_NAME'];
  1528. // 总价
  1529. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  1530. $orderAmount += $totalAmount;
  1531. $orderNums += $value['BUY_NUMS'];
  1532. // 税额
  1533. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  1534. $totalTaxAmount += $taxAmount;
  1535. $totalBv = $value['BUY_NUMS'] * $value['REAL_PV'];
  1536. $orderTotalBv += $totalBv;
  1537. $orderTotalTaxAmount += $taxAmount;
  1538. $orderTotalAmount += $totalAmount - $taxAmount;
  1539. $orderTotal += $totalAmount;
  1540. $totalBvFormat = Tool::formatAmount($totalBv);
  1541. $taxableAmountFormat =Tool::formatAmount($taxAmount);
  1542. $vatAmountFormat = Tool::formatAmount($totalAmount - $taxAmount);
  1543. $totalFormat = Tool::formatAmount($totalAmount);
  1544. $vatRateFormat = Tool::formatAmount($value['TAX_RATE']) . '%';
  1545. $unitPriceFormat = Tool::formatAmount($value['REAL_PRICE']);
  1546. $unitBvFormat = Tool::formatAmount($value['REAL_PV']);
  1547. // 订单详情
  1548. $orderDetails .= <<<EOT
  1549. <tr style="text-align: left; padding: 10px 5px; font-weight: normal; font-size: 12px; width: 100%;">
  1550. <td style="width: 30px;">{$no}</td>
  1551. <td>{$value['SKU_CODE']}</td>
  1552. <td>{$value['GOODS_TITLE']}</td>
  1553. <td>{$value['BUY_NUMS']}</td>
  1554. <td>{$unitPriceFormat}</td>
  1555. <td>{$unitBvFormat}</td>
  1556. <td>{$totalBvFormat}</td>
  1557. <td>{$taxableAmountFormat}</td>
  1558. <td>{$vatRateFormat}</td>
  1559. <td>{$vatAmountFormat}</td>
  1560. <td>{$totalFormat}</td>
  1561. </tr>
  1562. EOT;
  1563. }
  1564. $memberCode = Yii::t('app', 'memberCode');
  1565. $memberName = Yii::t('app', 'memberName');
  1566. $memberAddress = Yii::t('app', 'memberAddress');
  1567. $memberPhone = Yii::t('app', 'memberPhone');
  1568. $orderCode = Yii::t('app', 'orderCode');
  1569. $taxInvoice = Yii::t('app', 'taxInvoice');
  1570. $productCode = Yii::t('app', 'productCode');
  1571. $productName = Yii::t('app', 'productName');
  1572. $productPrice = Yii::t('app', 'productPrice');
  1573. $quantity = Yii::t('app', 'qty');
  1574. $taxRate = Yii::t('app', 'taxRate');
  1575. $totalTax = Yii::t('app', 'totalTax');
  1576. $totalAmount = Yii::t('app', 'totalAmount');
  1577. $total = Yii::t('app', 'total');
  1578. $signature = Yii::t('app', 'signature');
  1579. $date = Yii::t('app', 'date');
  1580. $createAt = Yii::t('app', 'createAt');
  1581. $l['a_meta_charset'] = 'UTF-8';
  1582. $l['a_meta_dir'] = 'ltr';
  1583. $l['a_meta_language'] = 'zh';
  1584. $l['w_page'] = '页面';
  1585. $orderAmount = Tool::formatAmount($orderAmount);
  1586. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  1587. $orderTotalBv = Tool::formatAmount($orderTotalBv);
  1588. $orderTotalTaxAmount = Tool::formatAmount($orderTotalTaxAmount);
  1589. $orderTotalAmount = Tool::formatAmount($orderTotalAmount);
  1590. $orderTotal = Tool::formatAmount($orderTotal);
  1591. $context = <<<ORDER
  1592. <!doctype html>
  1593. <html lang="en">
  1594. <head>
  1595. <meta charset="UTF-8" />
  1596. <title>{$taxInvoice}</title>
  1597. <style>
  1598. table {
  1599. border-collapse: collapse;
  1600. }
  1601. table td, table th {
  1602. border: 1px solid #ccc;
  1603. border-collapse: collapse;
  1604. }
  1605. .bg {
  1606. background-color: #ccc;
  1607. }
  1608. /* 无边框表格样式类 */
  1609. .table-noborder {
  1610. border-collapse: collapse; /* 合并边框(避免残留间隙) */
  1611. border-spacing: 0; /* 清除单元格之间的默认间隙 */
  1612. empty-cells: show; /* 不影响空单元格(可选,避免意外显示) */
  1613. }
  1614. /* 清除 table、th、td 的所有边框 */
  1615. .table-noborder,
  1616. .table-noborder th,
  1617. .table-noborder td {
  1618. border: none !important; /* !important 可选,用于覆盖冲突样式 */
  1619. outline: none; /* 清除可能的默认轮廓(可选) */
  1620. }
  1621. </style>
  1622. </head>
  1623. <body style="font-weight: normal; margin: 0; padding: 0; line-height: 1.3;">
  1624. <div class="content" style="line-height: 1.3; font-weight: normal;">
  1625. <p style="text-align: left; font-weight: bold; font-size: 18px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;"><b>Tax Invoice</b></p>
  1626. <p style="text-align: left; font-weight: bold; font-size: 15px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;"><b>Elken Arabiya General Grading Co.LLC</b></p>
  1627. <p style="text-align: left; font-size: 13px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;">Shop No.2, Plot 356-1142, Juneirah Street, Umm Suqeim 1, Dubai, UAE</p>
  1628. <p style="text-align: left; font-size: 13px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;">Phone: +971042296118</p>
  1629. <p style="text-align: left; font-size: 13px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;">License No: 1314319</p>
  1630. <p style="text-align: left; font-size: 13px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;">VAT No: {$orderSn}</p>
  1631. <hr />
  1632. <br>
  1633. <br>
  1634. <div style="width: 100%; line-height: 15px; margin-left: 0; margin-right: 0; margin-top: 0; margin-bottom: 0; padding: 0;">
  1635. <table class="table-noborder" width="100%">
  1636. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1637. <td>
  1638. Bill to
  1639. </td>
  1640. <td>
  1641. Invoice No.: {$invoiceNo}
  1642. </td>
  1643. </tr>
  1644. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1645. <td>
  1646. Name of Distributor: {$userName}
  1647. </td>
  1648. <td>
  1649. Date: {$orderAt}
  1650. </td>
  1651. </tr>
  1652. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1653. <td>
  1654. Member ID: {$userId}
  1655. </td>
  1656. <td>
  1657. Payment status: {$paymentStatus}
  1658. </td>
  1659. </tr>
  1660. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1661. <td colspan="2">
  1662. Address: {$address}
  1663. </td>
  1664. </tr>
  1665. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1666. <td colspan="2">
  1667. Contact: {$mobile}
  1668. </td>
  1669. </tr>
  1670. </table>
  1671. <br />
  1672. <br />
  1673. <br />
  1674. <table border="1" width="100%">
  1675. <tr style="text-align: left; font-weight: normal; font-size: 12px; width: 100%; padding: 5px 5px;">
  1676. <th style="width: 30px;">No.</th>
  1677. <th>Product Code</th>
  1678. <th>Product Name</th>
  1679. <th>Quantity</th>
  1680. <th>Unit Price({$currency})</th>
  1681. <th>Unit BV</th>
  1682. <th>Total BV</th>
  1683. <th>Taxable Amount({$currency})</th>
  1684. <th>VAT Rate</th>
  1685. <th>VAT Amount({$currency})</th>
  1686. <th>Total({$currency})</th>
  1687. </tr>
  1688. {$orderDetails}
  1689. </table>
  1690. <table style="table-layout: fixed;" class="table-noborder">
  1691. <tr><td colspan="11"></td></tr>
  1692. <tr><td colspan="11"></td></tr>
  1693. </table>
  1694. <table style="table-layout: fixed;">
  1695. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1696. <td class="table-noborder" style="width: 30px;"></td>
  1697. <td style="text-align: left; background-color: lightslategray;" colspan="2">Grand Total</td>
  1698. <td style="text-align: left; background-color: lightslategray;">{$orderTotalQuantity}</td>
  1699. <td style="text-align: left; background-color: lightslategray;"></td>
  1700. <td style="text-align: left; background-color: lightslategray;"></td>
  1701. <td style="text-align: left; background-color: lightslategray;">{$orderTotalBv}</td>
  1702. <td style="text-align: left; background-color: lightslategray;">{$orderTotalTaxAmount}</td>
  1703. <td style="text-align: left; background-color: lightslategray;"></td>
  1704. <td style="text-align: left; background-color: lightslategray;">{$orderTotalAmount}</td>
  1705. <td style="text-align: left; background-color: lightslategray;">{$orderTotal}</td>
  1706. </tr>
  1707. </table>
  1708. <table style="table-layout: fixed;" class="table-noborder">
  1709. <tr>
  1710. <td colspan="11"></td>
  1711. </tr>
  1712. </table>
  1713. <table style="table-layout: fixed;">
  1714. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1715. <td colspan="7" class="table-noborder"></td>
  1716. <td style="text-align: left; background-color: lightgoldenrodyellow;" colspan="2" >Total Amount</td>
  1717. <td style="text-align: left; background-color: lightgoldenrodyellow;" colspan="2">{$currency}{$orderAmount}</td>
  1718. </tr>
  1719. </table>
  1720. <table style="table-layout: fixed;" class="table-noborder">
  1721. <tr>
  1722. <td colspan="11"></td>
  1723. </tr>
  1724. </table>
  1725. <table style="table-layout: fixed;" class="table-noborder">
  1726. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1727. <td colspan="7"></td>
  1728. <td colspan="2">Method:</td>
  1729. <td colspan="2"></td>
  1730. </tr>
  1731. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1732. <td colspan="7"></td>
  1733. <td colspan="2" >Paid amount:</td>
  1734. <td colspan="2">{$currency}{$orderAmount}</td>
  1735. </tr>
  1736. </table>
  1737. <table style="table-layout: fixed;" class="table-noborder">
  1738. <tr>
  1739. <td colspan="11"></td>
  1740. </tr>
  1741. </table>
  1742. <table style="table-layout: fixed;" class="table-noborder">
  1743. <tr style="text-align: left; font-weight: normal; font-size: 12px; margin-top: 15px;">
  1744. <td colspan="2">Remark:</td>
  1745. <td colspan="9"></td>
  1746. </tr>
  1747. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1748. <td colspan="7">{$invoiceRemark}</td>
  1749. <td colspan="4"></td>
  1750. </tr>
  1751. </table>
  1752. <table style="table-layout: fixed;" class="table-noborder">
  1753. <tr>
  1754. <td colspan="11"></td>
  1755. </tr>
  1756. <tr>
  1757. <td colspan="11"></td>
  1758. </tr>
  1759. <tr>
  1760. <td colspan="11"></td>
  1761. </tr>
  1762. <tr>
  1763. <td colspan="11"></td>
  1764. </tr>
  1765. </table>
  1766. <table style="table-layout: fixed;" class="table-noborder">
  1767. <tr style="text-align: left; font-weight: normal; font-size: 12px; margin-top: 15px;">
  1768. <td colspan="4">Issued By:</td>
  1769. <td colspan="4">Picked By:</td>
  1770. <td colspan="3">Received By:</td>
  1771. </tr>
  1772. <tr>
  1773. <td colspan="11"></td>
  1774. </tr>
  1775. </table>
  1776. </div>
  1777. </div>
  1778. </body>
  1779. </html>
  1780. ORDER;
  1781. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  1782. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1783. // 设置打印模式
  1784. $pdf->SetCreator(PDF_CREATOR);
  1785. $pdf->SetAuthor('DaZe');
  1786. $pdf->SetTitle($orderSn);
  1787. $pdf->SetSubject('TCPDF Tutorial');
  1788. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  1789. // 是否显示页眉
  1790. $pdf->setPrintHeader(false);
  1791. // 设置页眉字体
  1792. $pdf->setHeaderFont(Array('Helvetica', '', '12'));
  1793. // 页眉距离顶部的距离
  1794. $pdf->SetHeaderMargin('5');
  1795. // 是否显示页脚
  1796. $pdf->setPrintFooter(false);
  1797. // 设置默认等宽字体
  1798. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  1799. // 设置行高
  1800. // $pdf->setCellHeightRatio(1);
  1801. // 设置左、上、右的间距
  1802. $pdf->SetMargins('10', '0', '10');
  1803. // 设置是否自动分页 距离底部多少距离时分页
  1804. $pdf->SetAutoPageBreak(TRUE, '15');
  1805. // 设置图像比例因子
  1806. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1807. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  1808. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  1809. $pdf->setLanguageArray($l);
  1810. }
  1811. $pdf->setFontSubsetting(true);
  1812. $pdf->AddPage();
  1813. // 设置字体
  1814. $pdf->SetFont('Helvetica', '', 10, '', true);
  1815. // $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  1816. // $image = file_get_contents($image_file);
  1817. // $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  1818. $pdf->writeHTML($context);
  1819. $result = $pdf->Output($realFile, 'F');
  1820. $this->_updateFirst($realFile, 1);
  1821. }
  1822. $this->complete();
  1823. return true;
  1824. }
  1825. }