BaseExport.php 93 KB

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