BaseExport.php 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  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. echo('sql:' . $rawSql);
  1477. $oderList = $query->all();
  1478. $sn = $oderList[0]['SN'];
  1479. // 同时使用原生SQL查询进行对比测试
  1480. $nativeConnection = Yii::$app->db;
  1481. $nativeQuery = "
  1482. SELECT
  1483. `OG`.`ID` AS `AID`,
  1484. `O`.*,
  1485. `U`.`REAL_NAME`,
  1486. `U`.`DEC_ID`,
  1487. `SG`.`CATEGORY_TYPE`,
  1488. `OG`.`REAL_PRICE`,
  1489. `OG`.`TAX_RATE`,
  1490. `OG`.`BUY_NUMS`,
  1491. `OG`.`SKU_CODE`,
  1492. `OG`.`GOODS_TITLE`,
  1493. `OG`.`REAL_PV`
  1494. FROM
  1495. `AR_ORDER_GOODS` `OG`
  1496. LEFT JOIN `AR_ORDER` `O` ON OG.ORDER_SN = O.SN
  1497. LEFT JOIN `AR_USER` `U` ON U.ID = O.USER_ID
  1498. LEFT JOIN `AR_SHOP_GOODS` `SG` ON SG.ID = OG.GOODS_ID
  1499. WHERE
  1500. O.IS_DELETE = 0
  1501. AND O.SN = '{$sn}'
  1502. ORDER BY
  1503. `O`.`CREATED_AT` DESC";
  1504. $nativeResults = $nativeConnection->createCommand($nativeQuery)->queryAll();
  1505. // 如果原生查询有结果但Yii查询没有,使用原生查询结果
  1506. if(count($nativeResults) > 0 && count($oderList) < count($nativeResults)) {
  1507. $oderList = $nativeResults;
  1508. }
  1509. if ($oderList) {
  1510. $userId = '';
  1511. $userName = '';
  1512. $address = '';
  1513. $mobile = $oderList[0]['MOBILE'];
  1514. $orderAt = Date::convert($oderList[0]['CREATED_AT'],'d/m/Y');
  1515. $orderDetails = '';
  1516. $orderDetails_bv = '';
  1517. $orderSn = $oderList[0]['SN'];;
  1518. $orderAmount = 0; // 合计总额
  1519. $orderNums = 0; // 合计总数
  1520. $totalTaxAmount = 0; // 合计税额
  1521. $totalAmount = 0;
  1522. $paymentStatus = 'Paid'; // 支付状态
  1523. $invoiceRemark = $oderList[0]['INVOICE_REMARK'];
  1524. $paymentMethod = $oderList[0]['METHOD']??'Cash'; // 支付方式
  1525. $currency = Currency::findOne($oderList[0]['CURRENCY_ID'])['CODE'] ?? '';;
  1526. $invoiceNo = $oderList[0]['INVOICE_NO'];
  1527. $provinceName = $oderList[0]['PROVINCE'] ? Region::getCnName($oderList[0]['PROVINCE']) : '';
  1528. $cityName = $oderList[0]['CITY'] ? Region::getCnName($oderList[0]['CITY']) : '';
  1529. $countyName = $oderList[0]['COUNTY'] ? Region::getCnName($oderList[0]['COUNTY']) : '';
  1530. $address = $provinceName . $cityName . $countyName . $oderList[0]['ADDRESS'];
  1531. $paymentStatus = \Yii::$app->params['orderStatus'][$oderList[0]['STATUS']]['label'] ?? 'Paid';
  1532. $orderTotalBv = 0;
  1533. $orderTotalTaxAmount = 0;
  1534. $orderTotalAmount = 0;
  1535. $orderTotal = 0;
  1536. $orderTotalQuantity = count($oderList);
  1537. $no = 0;
  1538. foreach ($oderList as $key => $value) {
  1539. $no += 1;
  1540. $userId = $value['USER_NAME'];
  1541. $userName = $value['REAL_NAME'];
  1542. // 总价
  1543. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  1544. $orderAmount += $totalAmount;
  1545. $orderNums += $value['BUY_NUMS'];
  1546. // 税额
  1547. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  1548. $totalTaxAmount += $taxAmount;
  1549. $totalBv = $value['BUY_NUMS'] * $value['REAL_PV'];
  1550. $orderTotalBv += $totalBv;
  1551. $orderTotalTaxAmount += $taxAmount;
  1552. $orderTotalAmount += $totalAmount - $taxAmount;
  1553. $orderTotal += $totalAmount;
  1554. $totalBvFormat = Tool::formatAmount($totalBv);
  1555. $taxableAmountFormat =Tool::formatAmount($taxAmount);
  1556. $vatAmountFormat = Tool::formatAmount($totalAmount - $taxAmount);
  1557. $totalFormat = Tool::formatAmount($totalAmount);
  1558. $vatRateFormat = Tool::formatAmount($value['TAX_RATE']) . '%';
  1559. $unitPriceFormat = Tool::formatAmount($value['REAL_PRICE']);
  1560. $unitBvFormat = Tool::formatAmount($value['REAL_PV']);
  1561. // 订单详情
  1562. //ek-3391 Taxable Amount和VAT Amount字段取值错误(两个取值取反了),需要修改 (2025/11/25 13:35 Ryan)
  1563. $orderDetails .= <<<EOT
  1564. <tr style="text-align: left; font-weight: normal; font-size: 12px; width: 100%; padding: 5px 5px;">
  1565. <td style="white-space: nowrap;">{$no}</td>
  1566. <td>{$value['SKU_CODE']}</td>
  1567. <td>{$value['GOODS_TITLE']}</td>
  1568. <td>{$value['BUY_NUMS']}</td>
  1569. <td>{$unitPriceFormat}</td>
  1570. <!-- <td>{$unitBvFormat}</td>-->
  1571. <!-- <td>{$totalBvFormat}</td>-->
  1572. <td colspan="2">{$vatAmountFormat}</td>
  1573. <td>{$vatRateFormat}</td>
  1574. <td colspan="2">{$taxableAmountFormat}</td>
  1575. <td>{$totalFormat}</td>
  1576. </tr>
  1577. EOT;
  1578. $orderDetails_bv .= <<<EOT
  1579. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1580. <td colspan="7" class="table-noborder"></td>
  1581. <td>{$value['SKU_CODE']}</td>
  1582. <td>{$value['BUY_NUMS']}</td>
  1583. <td>{$unitBvFormat}</td>
  1584. <td>{$totalBvFormat}</td>
  1585. </tr>
  1586. EOT;
  1587. }
  1588. $memberCode = Yii::t('app', 'memberCode');
  1589. $memberName = Yii::t('app', 'memberName');
  1590. $memberAddress = Yii::t('app', 'memberAddress');
  1591. $memberPhone = Yii::t('app', 'memberPhone');
  1592. $orderCode = Yii::t('app', 'orderCode');
  1593. $taxInvoice = Yii::t('app', 'taxInvoice');
  1594. $productCode = Yii::t('app', 'productCode');
  1595. $productName = Yii::t('app', 'productName');
  1596. $productPrice = Yii::t('app', 'productPrice');
  1597. $quantity = Yii::t('app', 'qty');
  1598. $taxRate = Yii::t('app', 'taxRate');
  1599. $totalTax = Yii::t('app', 'totalTax');
  1600. $totalAmount = Yii::t('app', 'totalAmount');
  1601. $total = Yii::t('app', 'total');
  1602. $signature = Yii::t('app', 'signature');
  1603. $date = Yii::t('app', 'date');
  1604. $createAt = Yii::t('app', 'createAt');
  1605. $l['a_meta_charset'] = 'UTF-8';
  1606. $l['a_meta_dir'] = 'ltr';
  1607. $l['a_meta_language'] = 'zh';
  1608. $l['w_page'] = '页面';
  1609. $orderAmount = Tool::formatAmount($orderAmount);
  1610. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  1611. $orderTotalBv = Tool::formatAmount($orderTotalBv);
  1612. $orderTotalTaxAmount = Tool::formatAmount($orderTotalTaxAmount);
  1613. $orderTotalAmount = Tool::formatAmount($orderTotalAmount);
  1614. $orderTotal = Tool::formatAmount($orderTotal);
  1615. $context = <<<ORDER
  1616. <!doctype html>
  1617. <html lang="en">
  1618. <head>
  1619. <meta charset="UTF-8" />
  1620. <title>{$taxInvoice}</title>
  1621. <style>
  1622. table {
  1623. border-collapse: collapse;
  1624. }
  1625. table td, table th {
  1626. border: 1px solid #ccc;
  1627. border-collapse: collapse;
  1628. }
  1629. .bg {
  1630. background-color: #ccc;
  1631. }
  1632. /* 无边框表格样式类 */
  1633. .table-noborder {
  1634. border-collapse: collapse; /* 合并边框(避免残留间隙) */
  1635. border-spacing: 0; /* 清除单元格之间的默认间隙 */
  1636. empty-cells: show; /* 不影响空单元格(可选,避免意外显示) */
  1637. }
  1638. /* 清除 table、th、td 的所有边框 */
  1639. .table-noborder,
  1640. .table-noborder th,
  1641. .table-noborder td {
  1642. border: none !important; /* !important 可选,用于覆盖冲突样式 */
  1643. outline: none; /* 清除可能的默认轮廓(可选) */
  1644. }
  1645. </style>
  1646. </head>
  1647. <body style="font-weight: normal; margin: 0; padding: 0; line-height: 1.3;">
  1648. <div class="content" style="line-height: 1.3; font-weight: normal;">
  1649. <div style="display: flex; justify-content: space-between; align-items: flex-start; width: 100%;">
  1650. <div style="width: 70%;">
  1651. <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>
  1652. <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>
  1653. <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>
  1654. <p style="text-align: left; font-size: 13px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;">Phone: +971042296118</p>
  1655. <p style="text-align: left; font-size: 13px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;">License No: 1314319</p>
  1656. <p style="text-align: left; font-size: 13px; margin: 0 !important; padding: 0 !important; line-height: 1.3 !important;">TRN No: 105034822400003</p>
  1657. </div>
  1658. <div style="width: 25%; text-align: right;">
  1659. <!-- 图像将通过TCPDF直接插入 -->
  1660. </div>
  1661. </div>
  1662. <hr />
  1663. <br>
  1664. <br>
  1665. <div style="width: 100%; line-height: 15px; margin-left: 0; margin-right: 0; margin-top: 0; margin-bottom: 0; padding: 0;">
  1666. <table class="table-noborder" width="100%">
  1667. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1668. <td>
  1669. Bill to
  1670. </td>
  1671. <td>
  1672. </td>
  1673. </tr>
  1674. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1675. <td>
  1676. Name of Distributor: {$userName}
  1677. </td>
  1678. <td>
  1679. Invoice No.: {$invoiceNo}
  1680. </td>
  1681. </tr>
  1682. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1683. <td>
  1684. Member ID: {$userId}
  1685. </td>
  1686. <td>
  1687. Order No.: {$orderSn}
  1688. </td>
  1689. </tr>
  1690. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1691. <td>
  1692. Address: {$address}
  1693. </td>
  1694. <td>
  1695. Date: {$orderAt}
  1696. </td>
  1697. </tr>
  1698. <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
  1699. <td>
  1700. Contact: {$mobile}
  1701. </td>
  1702. <td>
  1703. Payment status: {$paymentStatus}
  1704. </td>
  1705. </tr>
  1706. </table>
  1707. <br />
  1708. <br />
  1709. <br />
  1710. <table style="table-layout: fixed;" width="100%">
  1711. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1712. <th style="width: 5%; white-space: nowrap;">No.</th>
  1713. <th style="width: 10%; white-space: normal; word-break: break-word;">Product Code</th>
  1714. <th style="width: 19%; white-space: normal; word-break: break-word;">Product Name</th>
  1715. <th style="width: 8%; white-space: nowrap;">Quantity</th>
  1716. <th style="width: 10%; white-space: normal; word-break: break-word;">Unit Price ({$currency})</th>
  1717. <th style="width: 14%; white-space: normal; word-break: break-word;" colspan="2">Taxable Amount ({$currency})</th>
  1718. <th style="width: 8%; white-space: normal; word-break: break-word;">VAT Rate</th>
  1719. <th style="width: 16%; white-space: normal; word-break: break-word;" colspan="2">VAT Amount ({$currency})</th>
  1720. <th style="width: 10%; white-space: normal; word-break: break-word;">Total ({$currency})</th>
  1721. </tr>
  1722. {$orderDetails}
  1723. </table>
  1724. <table style="table-layout: fixed;" class="table-noborder">
  1725. <tr><td colspan="11"></td></tr>
  1726. <tr><td colspan="11"></td></tr>
  1727. </table>
  1728. <table style="table-layout: fixed;">
  1729. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1730. <td class="table-noborder" style="width: 5%; white-space: nowrap;"></td>
  1731. <td style="width: 29%; text-align: left; background-color: lightslategray;" colspan="2">Grand Total</td>
  1732. <td style="width: 8%; text-align: left; background-color: lightslategray;">{$orderTotalQuantity}</td>
  1733. <td style="width: 10%; text-align: left; background-color: lightslategray;"></td>
  1734. <td style="width: 14%; text-align: left; background-color: lightslategray;" colspan="2">{$orderTotalAmount}</td>
  1735. <td style="width: 8%; text-align: left; background-color: lightslategray;"></td>
  1736. <td style="width: 16%; text-align: left; background-color: lightslategray;" colspan="2">{$orderTotalTaxAmount}</td>
  1737. <td style="width: 10%; text-align: left; background-color: lightslategray;">{$orderTotal}</td>
  1738. </tr>
  1739. </table>
  1740. <table style="table-layout: fixed;" class="table-noborder">
  1741. <tr>
  1742. <td colspan="11"></td>
  1743. </tr>
  1744. </table>
  1745. <table style="table-layout: fixed;" width="100%">
  1746. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1747. <td colspan="7" class="table-noborder"></td>
  1748. <td style="text-align: left; background-color: lightgoldenrodyellow;" colspan="2" >Total Amount</td>
  1749. <td style="text-align: left; background-color: lightgoldenrodyellow;" colspan="2">{$currency}{$orderAmount}</td>
  1750. </tr>
  1751. </table>
  1752. <table style="table-layout: fixed;" class="table-noborder">
  1753. <tr>
  1754. <td colspan="11"></td>
  1755. </tr>
  1756. </table>
  1757. <table style="table-layout: fixed;" class="table-noborder">
  1758. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1759. <td colspan="7"></td>
  1760. <td colspan="2">Method:</td>
  1761. <td colspan="2">{$paymentMethod}</td>
  1762. </tr>
  1763. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1764. <td colspan="7"></td>
  1765. <td colspan="2" >Paid amount:</td>
  1766. <td colspan="2">{$currency}{$orderAmount}</td>
  1767. </tr>
  1768. </table>
  1769. <table style="table-layout: fixed;" class="table-noborder">
  1770. <tr>
  1771. <td colspan="11"></td>
  1772. </tr>
  1773. </table>
  1774. <table style="table-layout: fixed;">
  1775. <tr style="text-align: left; font-weight: normal; font-size: 12px; margin-top: 15px;">
  1776. <td colspan="7" class="table-noborder"></td>
  1777. <td>Product Code</td>
  1778. <td>Quantity</td>
  1779. <td>Unit BV</td>
  1780. <td>Total BV</td>
  1781. </tr>
  1782. $orderDetails_bv
  1783. </table>
  1784. <table style="table-layout: fixed;" class="table-noborder">
  1785. <tr><td colspan="11"></td></tr>
  1786. <tr><td colspan="11"></td></tr>
  1787. </table>
  1788. <table style="table-layout: fixed;">
  1789. <tr style="text-align: center; font-weight: normal; font-size: 12px;">
  1790. <td class="table-noborder" colspan="7"></td>
  1791. <td style="text-align: center; background-color: lightslategray;" colspan="2">Grand Total BV</td>
  1792. <td style="text-align: center; background-color: lightslategray;" colspan="2">{$orderTotalBv}</td>
  1793. </tr>
  1794. </table>
  1795. <table style="table-layout: fixed;">
  1796. <tr style="text-align: left; font-weight: normal; font-size: 12px; margin-top: 15px;">
  1797. <td colspan="2" class="table-noborder">Remark:</td>
  1798. <td colspan="9" class="table-noborder"></td>
  1799. </tr>
  1800. <tr style="text-align: left; font-weight: normal; font-size: 12px;">
  1801. <td colspan="6" class="table-noborder">{$invoiceRemark}</td>
  1802. </tr>
  1803. </table>
  1804. <table style="table-layout: fixed;" class="table-noborder">
  1805. <tr>
  1806. <td colspan="11"></td>
  1807. </tr>
  1808. <tr>
  1809. <td colspan="11"></td>
  1810. </tr>
  1811. <tr>
  1812. <td colspan="11"></td>
  1813. </tr>
  1814. <tr>
  1815. <td colspan="11"></td>
  1816. </tr>
  1817. </table>
  1818. <table style="table-layout: fixed;" class="table-noborder">
  1819. <tr style="text-align: left; font-weight: normal; font-size: 12px; margin-top: 15px;">
  1820. <td colspan="4">Issued By:</td>
  1821. <td colspan="4">Picked By:</td>
  1822. <td colspan="3">Received By:</td>
  1823. </tr>
  1824. <tr>
  1825. <td colspan="11"></td>
  1826. </tr>
  1827. </table>
  1828. </div>
  1829. </div>
  1830. </body>
  1831. </html>
  1832. ORDER;
  1833. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  1834. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1835. // 设置打印模式
  1836. $pdf->SetCreator(PDF_CREATOR);
  1837. $pdf->SetAuthor('DaZe');
  1838. $pdf->SetTitle($orderSn);
  1839. $pdf->SetSubject('TCPDF Tutorial');
  1840. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  1841. // 是否显示页眉
  1842. $pdf->setPrintHeader(false);
  1843. // 设置页眉字体
  1844. $pdf->setHeaderFont(Array('Helvetica', '', '12'));
  1845. // 页眉距离顶部的距离
  1846. $pdf->SetHeaderMargin('5');
  1847. // 是否显示页脚
  1848. $pdf->setPrintFooter(false);
  1849. // 设置默认等宽字体
  1850. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  1851. // 设置行高
  1852. // $pdf->setCellHeightRatio(1);
  1853. // 设置左、上、右的间距
  1854. $pdf->SetMargins('10', '0', '10');
  1855. // 设置是否自动分页 距离底部多少距离时分页
  1856. $pdf->SetAutoPageBreak(TRUE, '15');
  1857. // 设置图像比例因子
  1858. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1859. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  1860. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  1861. $pdf->setLanguageArray($l);
  1862. }
  1863. $pdf->setFontSubsetting(true);
  1864. $pdf->AddPage();
  1865. // 设置字体
  1866. $pdf->SetFont('Helvetica', '', 10, '', true);
  1867. // $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  1868. // $image = file_get_contents($image_file);
  1869. // $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  1870. $pdf->writeHTML($context);
  1871. $result = $pdf->Output($realFile, 'F');
  1872. $this->_updateFirst($realFile, 1);
  1873. }
  1874. $this->complete();
  1875. return true;
  1876. }
  1877. }