BaseExport.php 93 KB

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