BaseExport.php 93 KB

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