BaseExport.php 80 KB

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