BaseExport.php 89 KB

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