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 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('30', '35', '30');
  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('dejavusans', '', 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. // 将图像放在右上角,根据页面宽度和边距计算位置
  788. // $pdf->Image('@' . $image, $pdf->getPageWidth() - 45, 25, 30, 10, 'JPG');
  789. $pdf->writeHTML($context);
  790. $result = $pdf->Output($realFile, 'F');
  791. LoggerTool::debug(['result' => $result]);
  792. $this->_updateFirst($realFile, 1);
  793. }
  794. $this->complete();
  795. return true;
  796. }
  797. /**
  798. * 生成
  799. * @return bool
  800. * @throws Exception
  801. * @throws InvalidConfigException
  802. * @throws \yii\httpclient\Exception
  803. */
  804. public function generateDecOrderPDF() {
  805. $this->getParams();
  806. if (!$this->params) {
  807. throw new Exception('无法获取需要的参数');
  808. }
  809. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  810. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  811. $this->completed = false;
  812. $this->getExportId();
  813. $this->getUserId();
  814. $fileNameUpdated = false;
  815. // 获取列表数据及表头
  816. $this->_listModel = new $this->listModelClass();
  817. $this->_listModel->isExport = true;
  818. // 查询订单数据
  819. // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
  820. $orderQuery = Order::find()
  821. ->alias('O')
  822. ->where($this->params['condition'], $this->params['params'])
  823. ->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')
  824. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  825. ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  826. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  827. ->orderBy('O.CREATED_AT DESC');
  828. // 订单中间表只查询待支付和支付失败的订单
  829. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  830. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  831. $orderStandardQuery = ApproachOrder::find()
  832. ->alias('O')
  833. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  834. ->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')
  835. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  836. ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  837. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  838. ->orderBy('O.CREATED_AT DESC');
  839. $queryAll = $orderQuery->union($orderStandardQuery, true);
  840. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  841. $oderList = $query->all();
  842. if ($oderList) {
  843. $userId = '';
  844. $userName = '';
  845. $address = '';
  846. $mobile = '';
  847. $orderAt = '';
  848. $orderDetails = '';
  849. $orderSn = '';
  850. $orderAmount = 0; // 合计总额
  851. $orderNums = 0; // 合计总数
  852. $totalTaxAmount = 0; // 合计税额
  853. $totalAmount = 0;
  854. foreach ($oderList as $key => $value) {
  855. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  856. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  857. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  858. $userId = $value['USER_NAME'];
  859. $userName = $value['REAL_NAME'];
  860. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  861. $mobile = $value['MOBILE'];
  862. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  863. $orderSn = $value['SN'];
  864. // 总价
  865. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  866. $orderAmount += $totalAmount;
  867. $orderNums += $value['BUY_NUMS'];
  868. // 税额
  869. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  870. $totalTaxAmount += $taxAmount;
  871. $taxAmount = Tool::formatAmount($taxAmount);
  872. $totalAmount = Tool::formatAmount($totalAmount);
  873. // 订单详情
  874. $orderDetails .= <<<EOT
  875. <tr>
  876. <td>{$value['SKU_CODE']}</td>
  877. <td>{$value['GOODS_TITLE']}</td>
  878. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  879. <td>{$value['BUY_NUMS']}</td>
  880. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  881. <td style="text-align: right;">{$taxAmount}</td>
  882. <td style="text-align: right;">{$totalAmount}</td>
  883. </tr>
  884. EOT;
  885. }
  886. $memberCode = Yii::t('app', 'memberCode');
  887. $memberName = Yii::t('app', 'memberName');
  888. $memberAddress = Yii::t('app', 'memberAddress');
  889. $memberPhone = Yii::t('app', 'memberPhone');
  890. $orderCode = Yii::t('app', 'orderCode');
  891. $orderDetail = Yii::t('app', 'orderDetail');
  892. $productCode = Yii::t('app', 'productCode');
  893. $productName = Yii::t('app', 'productName');
  894. $productPrice = Yii::t('app', 'productPrice');
  895. $quantity = Yii::t('app', 'qty');
  896. $taxRate = Yii::t('app', 'taxRate');
  897. $totalTax = Yii::t('app', 'totalTax');
  898. $totalAmount = Yii::t('app', 'totalAmount');
  899. $total = Yii::t('app', 'total');
  900. $signature = Yii::t('app', 'signature');
  901. $date = Yii::t('app', 'date');
  902. $createAt = Yii::t('app', 'createAt');
  903. // 订单基本信息
  904. $orderBase = <<<ORDER
  905. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  906. <tr>
  907. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberCode}</td>
  908. <td width="70%">{$userId}</td>
  909. </tr>
  910. <tr>
  911. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberName}</td>
  912. <td width="70%">{$userName}</td>
  913. </tr>
  914. <tr>
  915. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberAddress}</td>
  916. <td width="70%">{$address}</td>
  917. </tr>
  918. <tr>
  919. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberPhone}</td>
  920. <td width="70%">{$mobile}</td>
  921. </tr>
  922. <tr>
  923. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$orderCode}</td>
  924. <td width="70%">{$orderSn}</td>
  925. </tr>
  926. <tr>
  927. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$createAt}</td>
  928. <td width="70%">{$orderAt}</td>
  929. </tr>
  930. <tr>
  931. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">{$orderDetail}</td>
  932. <td class="bg"></td>
  933. </tr>
  934. </table>
  935. ORDER;
  936. $l['a_meta_charset'] = 'UTF-8';
  937. $l['a_meta_dir'] = 'ltr';
  938. $l['a_meta_language'] = 'zh';
  939. $l['w_page'] = '页面';
  940. $orderAmount = sprintf('%.2f', $orderAmount);
  941. $totalTaxAmount = sprintf('%.2f', $totalTaxAmount);
  942. $context = <<<ORDER
  943. <!doctype html>
  944. <html lang="en">
  945. <head>
  946. <meta charset="UTF-8" />
  947. <title>{$orderDetail}</title>
  948. <style>
  949. table {
  950. border-collapse: collapse;
  951. }
  952. table td, table th {
  953. border: 1px solid #ccc;
  954. /*padding: 5px 5px;*/
  955. border-collapse: collapse;
  956. }
  957. /*td {*/
  958. /* padding: 120px;*/
  959. /*}*/
  960. .bg {
  961. background-color: #ccc;
  962. }
  963. </style>
  964. </head>
  965. <body>
  966. <div class="content">
  967. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>{$orderDetail}</b><br></p>
  968. <div>
  969. <div style="display: block; width: 100%;">
  970. {$orderBase}
  971. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  972. <tr>
  973. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productCode}</th>
  974. <th width="20%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productName}</th>
  975. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productPrice}</th>
  976. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">{$quantity}</th>
  977. <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">{$taxRate}</th>
  978. <th width="13%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalTax}</th>
  979. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalAmount}</th>
  980. </tr>
  981. {$orderDetails}
  982. <tr>
  983. <td colspan="3">{$total}</td>
  984. <td style="text-align: right;">{$orderNums}</td>
  985. <td></td>
  986. <td style="text-align: right;">{$totalTaxAmount}</td>
  987. <td style="text-align: right;">{$orderAmount}</td>
  988. </tr>
  989. </table>
  990. </div>
  991. <div style="width: 100%; margin-top: 50px; height: 30px;">
  992. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  993. <tr style="border: none;">
  994. <td width="70%" style="border: none;"></td>
  995. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$signature}:</td>
  996. </tr>
  997. <tr style="border: none;">
  998. <td width="70%" style="border: none;"></td>
  999. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$date}:</td>
  1000. </tr>
  1001. </table>
  1002. </div>
  1003. </div>
  1004. </div>
  1005. </body>
  1006. </html>
  1007. ORDER;
  1008. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  1009. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1010. // 设置打印模式
  1011. $pdf->SetCreator(PDF_CREATOR);
  1012. $pdf->SetAuthor('DaZe');
  1013. $pdf->SetTitle($orderSn);
  1014. $pdf->SetSubject('TCPDF Tutorial');
  1015. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  1016. // 是否显示页眉
  1017. $pdf->setPrintHeader(false);
  1018. // 设置页眉字体
  1019. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  1020. // 页眉距离顶部的距离
  1021. $pdf->SetHeaderMargin('5');
  1022. // 是否显示页脚
  1023. $pdf->setPrintFooter(false);
  1024. // 设置默认等宽字体
  1025. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  1026. // 设置行高
  1027. $pdf->setCellHeightRatio(1);
  1028. // 设置左、上、右的间距
  1029. $pdf->SetMargins('10', '10', '10');
  1030. // 设置是否自动分页 距离底部多少距离时分页
  1031. $pdf->SetAutoPageBreak(TRUE, '15');
  1032. // 设置图像比例因子
  1033. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1034. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  1035. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  1036. $pdf->setLanguageArray($l);
  1037. }
  1038. $pdf->setFontSubsetting(true);
  1039. $pdf->AddPage();
  1040. // 设置字体
  1041. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  1042. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1043. // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
  1044. // if (!file_exists($image_file)) {
  1045. // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
  1046. // }
  1047. $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  1048. $image = file_get_contents($image_file);
  1049. $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
  1050. $pdf->writeHTML($context);
  1051. $pdf->Output($realFile, 'F');
  1052. $this->_updateFirst($realFile, 1);
  1053. }
  1054. $this->complete();
  1055. return true;
  1056. }
  1057. /**
  1058. * 循环写入数据
  1059. * @param $realFile
  1060. * @param $fileNameUpdated
  1061. * @param int $page
  1062. * @param int $counter
  1063. * @return array
  1064. * @throws Exception
  1065. */
  1066. private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
  1067. if(method_exists($this->_listModel, 'getList')){
  1068. $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]);
  1069. } else {
  1070. throw new Exception($this->listModelClass.'的getList方法不存在');
  1071. }
  1072. return $list['list'];
  1073. }
  1074. /**
  1075. * 生成
  1076. * @return bool
  1077. * @throws Exception
  1078. * @throws InvalidConfigException
  1079. * @throws \yii\httpclient\Exception
  1080. */
  1081. public function generateBaOrderExcel() {
  1082. $this->getParams();
  1083. if (!$this->params) {
  1084. throw new Exception('无法获取需要的参数');
  1085. }
  1086. $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  1087. $path = __DS__ . $path;
  1088. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
  1089. $this->completed = false;
  1090. $this->getExportId();
  1091. $this->getUserId();
  1092. $this->_fp = fopen($realFile, 'w');
  1093. @exec('chown -R www:www /'.$realFile);
  1094. @exec('chmod -R 777 /'.$realFile);
  1095. // 获取列表数据及表头
  1096. $this->_listModel = new $this->listModelClass();
  1097. $this->_listModel->isExport = true;
  1098. if(method_exists($this->_listModel, 'getExportHeaders')){
  1099. if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
  1100. $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
  1101. }
  1102. $headers = $this->_listModel->getExportHeaders($this->userId);
  1103. fputcsv($this->_fp, $headers);
  1104. unset($headers);
  1105. $this->_updateFirst($realFile, 1);
  1106. } else {
  1107. throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
  1108. }
  1109. $this->_loopWriteDataBaOrder();
  1110. $this->complete();
  1111. return true;
  1112. }
  1113. /**
  1114. * 循环写入数据
  1115. */
  1116. private function _loopWriteDataBaOrder()
  1117. {
  1118. $orderQuery = BaOrder::find()
  1119. ->alias('O')
  1120. ->where($this->params['condition'], $this->params['params'])
  1121. ->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')
  1122. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1123. ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1124. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1125. ->orderBy('O.CREATED_AT DESC');
  1126. // 订单中间表只查询待支付和支付失败的订单
  1127. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  1128. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  1129. $orderStandardQuery = BaApproachOrder::find()
  1130. ->alias('O')
  1131. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  1132. ->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')
  1133. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1134. ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1135. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1136. ->orderBy('O.CREATED_AT DESC');
  1137. $queryAll = $orderQuery->union($orderStandardQuery, true);
  1138. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  1139. $lists = $query->all();
  1140. if(!empty($lists)){
  1141. $regionConfig = Cache::getRegionConfig();
  1142. foreach($lists as $columnData) {
  1143. $CREATE_USER_ID = Info::getBaUserIdByUserName($columnData['CREATE_USER']);
  1144. $createUserName = Info::getBaUserRealNameByUserId($CREATE_USER_ID);
  1145. $decUserName = Info::getBaUserNameByUserId($columnData['DEC_ID']);
  1146. $columnAccept = [
  1147. 'USER_NAME' => $columnData['USER_NAME'],
  1148. 'DEC_USER_NAME' => $decUserName,
  1149. 'CREATE_USER' => $columnData['CREATE_USER'],
  1150. 'CREATE_USER_NAME' => $createUserName,
  1151. 'SN' => $columnData['SN'],
  1152. 'STATUS' => Tool::paramConvert(\Yii::$app->params['orderStatus'])[$columnData['STATUS']]['label'] ?? '',
  1153. 'SKU_CODE' => $columnData['SKU_CODE'],
  1154. 'GOODS_TITLE' => $columnData['GOODS_TITLE'],
  1155. 'BUY_NUMS' => $columnData['BUY_NUMS'],
  1156. 'CONSIGNEE' => $columnData['CONSIGNEE'],
  1157. 'MOBILE' => "\t{$columnData['MOBILE']}",
  1158. 'TEL' => "\t{$columnData['TEL']}",
  1159. 'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
  1160. 'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
  1161. 'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
  1162. 'ADDRESS' => $columnData['ADDRESS'],
  1163. 'PERIOD_NUM' => $columnData['PERIOD_NUM'],
  1164. 'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Reselling': 'Points'),
  1165. 'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
  1166. 'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
  1167. 'PAY_AT' => $columnData['PAY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['PAY_AT']) : '',
  1168. 'DELIVERY_AT' => $columnData['DELIVERY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']) : '',
  1169. 'REAL_PRICE' => $columnData['REAL_PRICE'] ?? 0,
  1170. 'REAL_PV' => $columnData['REAL_PV'] ?? 0,
  1171. 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'] ?? 0,
  1172. 'TAX_RATE' => $columnData['TAX_RATE'],
  1173. 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
  1174. 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
  1175. 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
  1176. 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
  1177. 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
  1178. 'DELIVERY_STATUS_NAME' => Tool::paramConvert(\Yii::$app->params['deliveryStatus'])[$columnData['DELIVERY_STATUS']]['label'] ?? '',
  1179. ];
  1180. fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
  1181. unset($percent, $columnData, $columnAccept);
  1182. }
  1183. unset($list);
  1184. }
  1185. unset($list);
  1186. return 'finish';
  1187. }
  1188. /**
  1189. * 生成
  1190. * @return bool
  1191. * @throws Exception
  1192. * @throws InvalidConfigException
  1193. * @throws \yii\httpclient\Exception
  1194. */
  1195. public function generateBaOrderPDF()
  1196. {
  1197. $this->getParams();
  1198. if (!$this->params) {
  1199. throw new Exception('无法获取需要的参数');
  1200. }
  1201. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  1202. $realFile = $path . __DS__ . $this->getFileName('.pdf');
  1203. $this->completed = false;
  1204. $this->getExportId();
  1205. $this->getUserId();
  1206. $fileNameUpdated = false;
  1207. // 获取列表数据及表头
  1208. $this->_listModel = new $this->listModelClass();
  1209. $this->_listModel->isExport = true;
  1210. // 查询订单数据
  1211. $orderQuery = BaOrder::find()
  1212. ->alias('O')
  1213. ->where($this->params['condition'], $this->params['params'])
  1214. ->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')
  1215. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1216. ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1217. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1218. ->orderBy('O.CREATED_AT DESC');
  1219. // 订单中间表只查询待支付和支付失败的订单
  1220. $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
  1221. $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
  1222. $orderStandardQuery = BaApproachOrder::find()
  1223. ->alias('O')
  1224. ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
  1225. ->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')
  1226. ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1227. ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
  1228. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1229. ->orderBy('O.CREATED_AT DESC');
  1230. $queryAll = $orderQuery->union($orderStandardQuery, true);
  1231. $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
  1232. $oderList = $query->all();
  1233. if ($oderList) {
  1234. $userId = '';
  1235. $userName = '';
  1236. $address = '';
  1237. $mobile = '';
  1238. $orderAt = '';
  1239. $orderDetails = '';
  1240. $orderSn = '';
  1241. $orderAmount = 0; // 合计总额
  1242. $orderNums = 0; // 合计总数
  1243. $totalTaxAmount = 0; // 合计税额
  1244. $totalAmount = 0;
  1245. foreach ($oderList as $key => $value) {
  1246. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  1247. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  1248. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  1249. $userId = $value['USER_NAME'];
  1250. $userName = $value['REAL_NAME'];
  1251. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  1252. $mobile = $value['MOBILE'];
  1253. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  1254. $orderSn = $value['SN'];
  1255. // 总价
  1256. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  1257. $orderAmount += $totalAmount;
  1258. $orderNums += $value['BUY_NUMS'];
  1259. // 税额
  1260. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  1261. $totalTaxAmount += $taxAmount;
  1262. $taxAmount = Tool::formatAmount($taxAmount);
  1263. $totalAmount = Tool::formatAmount($totalAmount);
  1264. // 订单详情
  1265. $orderDetails .= <<<EOT
  1266. <tr>
  1267. <td>{$value['SKU_CODE']}</td>
  1268. <td>{$value['GOODS_TITLE']}</td>
  1269. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  1270. <td>{$value['BUY_NUMS']}</td>
  1271. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  1272. <td style="text-align: right;">{$taxAmount}</td>
  1273. <td style="text-align: right;">{$totalAmount}</td>
  1274. </tr>
  1275. EOT;
  1276. }
  1277. // 订单基本信息
  1278. $orderBase = <<<ORDER
  1279. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  1280. <tr>
  1281. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
  1282. <td width="70%">{$userId}</td>
  1283. </tr>
  1284. <tr>
  1285. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
  1286. <td width="70%">{$userName}</td>
  1287. </tr>
  1288. <tr>
  1289. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
  1290. <td width="70%">{$address}</td>
  1291. </tr>
  1292. <tr>
  1293. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
  1294. <td width="70%">{$mobile}</td>
  1295. </tr>
  1296. <tr>
  1297. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
  1298. <td width="70%">{$orderSn}</td>
  1299. </tr>
  1300. <tr>
  1301. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
  1302. <td width="70%">{$orderAt}</td>
  1303. </tr>
  1304. <tr>
  1305. <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
  1306. <td class="bg"></td>
  1307. </tr>
  1308. </table>
  1309. ORDER;
  1310. $l['a_meta_charset'] = 'UTF-8';
  1311. $l['a_meta_dir'] = 'ltr';
  1312. $l['a_meta_language'] = 'zh';
  1313. $l['w_page'] = '页面';
  1314. $orderAmount = Tool::formatAmount($orderAmount);
  1315. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  1316. $context = <<<ORDER
  1317. <!doctype html>
  1318. <html lang="en">
  1319. <head>
  1320. <meta charset="UTF-8" />
  1321. <title>Order detail</title>
  1322. <style>
  1323. table {
  1324. border-collapse: collapse;
  1325. }
  1326. table td, table th {
  1327. border: 1px solid #ccc;
  1328. padding: 5px 5px;
  1329. border-collapse: collapse;
  1330. }
  1331. /*td {*/
  1332. /* padding: 120px;*/
  1333. /*}*/
  1334. .bg {
  1335. background-color: #ccc;
  1336. }
  1337. </style>
  1338. </head>
  1339. <body>
  1340. <div class="content">
  1341. <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
  1342. <div>
  1343. <div style="display: block; width: 100%;">
  1344. {$orderBase}
  1345. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  1346. <tr>
  1347. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
  1348. <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
  1349. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
  1350. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
  1351. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
  1352. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
  1353. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
  1354. </tr>
  1355. {$orderDetails}
  1356. <tr>
  1357. <td colspan="3">Total</td>
  1358. <td>{$orderNums}</td>
  1359. <td></td>
  1360. <td style="text-align: right;">{$totalTaxAmount}</td>
  1361. <td style="text-align: right;">{$orderAmount}</td>
  1362. </tr>
  1363. </table>
  1364. </div>
  1365. <div style="width: 100%; margin-top: 50px; height: 30px;">
  1366. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  1367. <tr style="border: none;">
  1368. <td width="70%" style="border: none;"></td>
  1369. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
  1370. </tr>
  1371. <tr style="border: none;">
  1372. <td width="70%" style="border: none;"></td>
  1373. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
  1374. </tr>
  1375. </table>
  1376. </div>
  1377. </div>
  1378. </div>
  1379. </body>
  1380. </html>
  1381. ORDER;
  1382. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  1383. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1384. // 设置打印模式
  1385. $pdf->SetCreator(PDF_CREATOR);
  1386. $pdf->SetAuthor('DaZe');
  1387. $pdf->SetTitle($orderSn);
  1388. $pdf->SetSubject('TCPDF Tutorial');
  1389. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  1390. // 是否显示页眉
  1391. $pdf->setPrintHeader(false);
  1392. // 设置页眉字体
  1393. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  1394. // 页眉距离顶部的距离
  1395. $pdf->SetHeaderMargin('5');
  1396. // 是否显示页脚
  1397. $pdf->setPrintFooter(false);
  1398. // 设置默认等宽字体
  1399. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  1400. // 设置行高
  1401. $pdf->setCellHeightRatio(1);
  1402. // 设置左、上、右的间距
  1403. $pdf->SetMargins('10', '0', '10');
  1404. // 设置是否自动分页 距离底部多少距离时分页
  1405. $pdf->SetAutoPageBreak(TRUE, '15');
  1406. // 设置图像比例因子
  1407. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1408. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  1409. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  1410. $pdf->setLanguageArray($l);
  1411. }
  1412. $pdf->setFontSubsetting(true);
  1413. $pdf->AddPage();
  1414. // 设置字体
  1415. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  1416. // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
  1417. // if (!file_exists($image_file)) {
  1418. // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
  1419. // }
  1420. $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  1421. $image = file_get_contents($image_file);
  1422. $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  1423. $pdf->writeHTML($context);
  1424. $pdf->Output($realFile, 'F');
  1425. $this->_updateFirst($realFile, 1);
  1426. }
  1427. $this->complete();
  1428. return true;
  1429. }
  1430. /**
  1431. * 生成
  1432. * @return bool
  1433. * @throws Exception
  1434. * @throws InvalidConfigException
  1435. * @throws \yii\httpclient\Exception
  1436. */
  1437. public function actionOrderInvoiceExport() {
  1438. $this->getParams();
  1439. if (!$this->params) {
  1440. throw new Exception('无法获取需要的参数');
  1441. }
  1442. $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
  1443. $realFile = $this->mkdir($path) . __DS__ . $this->getFileName('.pdf');
  1444. $this->completed = false;
  1445. $this->getExportId();
  1446. $this->getUserId();
  1447. $fileNameUpdated = false;
  1448. // 获取列表数据及表头
  1449. $this->_listModel = new $this->listModelClass();
  1450. $this->_listModel->isExport = true;
  1451. // 查询订单数据
  1452. // 使用新的查询对象,禁用查询缓存,确保获取最新数据
  1453. $query = OrderGoods::find()
  1454. ->alias('OG')
  1455. ->where($this->params['condition'], $this->params['params'])
  1456. ->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')
  1457. ->join('LEFT JOIN', ORDER::tableName() . ' AS O', 'OG.ORDER_SN=O.SN')
  1458. ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
  1459. ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
  1460. ->asArray()
  1461. ->noCache(); // 禁用查询缓存
  1462. // 添加详细的调试信息
  1463. $rawSql = $query->createCommand()->getRawSql();
  1464. $oderList = $query->all();
  1465. $sn = $oderList[0]['SN'];
  1466. // 同时使用原生SQL查询进行对比测试
  1467. $nativeConnection = Yii::$app->db;
  1468. $nativeQuery = "
  1469. SELECT
  1470. `OG`.`ID` AS `AID`,
  1471. `O`.*,
  1472. `U`.`REAL_NAME`,
  1473. `U`.`DEC_ID`,
  1474. `SG`.`CATEGORY_TYPE`,
  1475. `OG`.`REAL_PRICE`,
  1476. `OG`.`TAX_RATE`,
  1477. `OG`.`BUY_NUMS`,
  1478. `OG`.`SKU_CODE`,
  1479. `OG`.`GOODS_TITLE`,
  1480. `OG`.`REAL_PV`
  1481. FROM
  1482. `AR_ORDER_GOODS` `OG`
  1483. LEFT JOIN `AR_ORDER` `O` ON OG.ORDER_SN = O.SN
  1484. LEFT JOIN `AR_USER` `U` ON U.ID = O.USER_ID
  1485. LEFT JOIN `AR_SHOP_GOODS` `SG` ON SG.ID = OG.GOODS_ID
  1486. WHERE
  1487. O.IS_DELETE = 0
  1488. AND O.SN = '{$sn}'
  1489. ORDER BY
  1490. `O`.`CREATED_AT` DESC";
  1491. $nativeResults = $nativeConnection->createCommand($nativeQuery)->queryAll();
  1492. // 如果原生查询有结果但Yii查询没有,使用原生查询结果
  1493. if(count($nativeResults) > 0 && count($oderList) < count($nativeResults)) {
  1494. $oderList = $nativeResults;
  1495. }
  1496. if ($oderList) {
  1497. $userId = '';
  1498. $userName = '';
  1499. $address = '';
  1500. $mobile = $oderList[0]['MOBILE'];
  1501. $orderAt = Date::convert($oderList[0]['CREATED_AT'],'Y/m/d');
  1502. $orderDetails = '';
  1503. $orderSn = $oderList[0]['SN'];;
  1504. $orderAmount = 0; // 合计总额
  1505. $orderNums = 0; // 合计总数
  1506. $totalTaxAmount = 0; // 合计税额
  1507. $totalAmount = 0;
  1508. $paymentStatus = 'Paid'; // 支付状态
  1509. $invoiceRemark = $oderList[0]['INVOICE_REMARK'];
  1510. $paymentMethod = $oderList[0]['PAY_TYPE']; // 支付方式
  1511. $currency = Currency::findOne($oderList[0]['CURRENCY_ID'])['CODE'] ?? '';;
  1512. $invoiceNo = $oderList[0]['INVOICE_NO'];
  1513. $provinceName = $oderList[0]['PROVINCE'] ? Region::getCnName($oderList[0]['PROVINCE']) : '';
  1514. $cityName = $oderList[0]['CITY'] ? Region::getCnName($oderList[0]['CITY']) : '';
  1515. $countyName = $oderList[0]['COUNTY'] ? Region::getCnName($oderList[0]['COUNTY']) : '';
  1516. $address = $provinceName . $cityName . $countyName . $oderList[0]['ADDRESS'];
  1517. $paymentMethod = $oderList[0]['PAY_TYPE'] ?? 'Cash';
  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"></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. }