BaseExport.php 93 KB

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