BaseExport.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  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. ->all();
  1460. if ($oderList) {
  1461. $userId = '';
  1462. $userName = '';
  1463. $address = '';
  1464. $mobile = '';
  1465. $orderAt = '';
  1466. $orderDetails = '';
  1467. $orderSn = '';
  1468. $orderAmount = 0; // 合计总额
  1469. $orderNums = 0; // 合计总数
  1470. $totalTaxAmount = 0; // 合计税额
  1471. $totalAmount = 0;
  1472. foreach ($oderList as $key => $value) {
  1473. $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
  1474. $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
  1475. $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
  1476. $userId = $value['USER_NAME'];
  1477. $userName = $value['REAL_NAME'];
  1478. $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
  1479. $mobile = $value['MOBILE'];
  1480. $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
  1481. $orderSn = $value['SN'];
  1482. // 总价
  1483. $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
  1484. $orderAmount += $totalAmount;
  1485. $orderNums += $value['BUY_NUMS'];
  1486. // 税额
  1487. $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
  1488. $totalTaxAmount += $taxAmount;
  1489. $taxAmount = Tool::formatAmount($taxAmount);
  1490. $totalAmount = Tool::formatAmount($totalAmount);
  1491. // 订单详情
  1492. $orderDetails .= <<<EOT
  1493. <tr>
  1494. <td width="10%" style="font-size: 14px; text-align: center;">{$key}</td>
  1495. <td>{$value['SKU_CODE']}</td>
  1496. <td>{$value['GOODS_TITLE']}</td>
  1497. <td>{$value['BUY_NUMS']}</td>
  1498. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  1499. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  1500. <td style="text-align: right;">{$value['REAL_PRICE']}</td>
  1501. <td style="text-align: right;">{$taxAmount}</td>
  1502. <td style="text-align: right;">{$value['TAX_RATE']}</td>
  1503. <td style="text-align: right;">{$taxAmount}</td>
  1504. <td style="text-align: right;">{$totalAmount}</td>
  1505. </tr>
  1506. EOT;
  1507. }
  1508. $memberCode = Yii::t('app', 'memberCode');
  1509. $memberName = Yii::t('app', 'memberName');
  1510. $memberAddress = Yii::t('app', 'memberAddress');
  1511. $memberPhone = Yii::t('app', 'memberPhone');
  1512. $orderCode = Yii::t('app', 'orderCode');
  1513. $taxInvoice = Yii::t('app', 'taxInvoice');
  1514. $productCode = Yii::t('app', 'productCode');
  1515. $productName = Yii::t('app', 'productName');
  1516. $productPrice = Yii::t('app', 'productPrice');
  1517. $quantity = Yii::t('app', 'qty');
  1518. $taxRate = Yii::t('app', 'taxRate');
  1519. $totalTax = Yii::t('app', 'totalTax');
  1520. $totalAmount = Yii::t('app', 'totalAmount');
  1521. $total = Yii::t('app', 'total');
  1522. $signature = Yii::t('app', 'signature');
  1523. $date = Yii::t('app', 'date');
  1524. $createAt = Yii::t('app', 'createAt');
  1525. // 订单基本信息
  1526. $orderBase = <<<ORDER
  1527. <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
  1528. <tr>
  1529. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberCode}</td>
  1530. <td width="70%">{$userId}</td>
  1531. </tr>
  1532. <tr>
  1533. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberName}</td>
  1534. <td width="70%">{$userName}</td>
  1535. </tr>
  1536. <tr>
  1537. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberAddress}</td>
  1538. <td width="70%">{$address}</td>
  1539. </tr>
  1540. <tr>
  1541. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberPhone}</td>
  1542. <td width="70%">{$mobile}</td>
  1543. </tr>
  1544. <tr>
  1545. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$orderCode}</td>
  1546. <td width="70%">{$orderSn}</td>
  1547. </tr>
  1548. <tr>
  1549. <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$createAt}</td>
  1550. <td width="70%">{$orderAt}</td>
  1551. </tr>
  1552. </table>
  1553. ORDER;
  1554. $l['a_meta_charset'] = 'UTF-8';
  1555. $l['a_meta_dir'] = 'ltr';
  1556. $l['a_meta_language'] = 'zh';
  1557. $l['w_page'] = '页面';
  1558. $orderAmount = Tool::formatAmount($orderAmount);
  1559. $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
  1560. $context = <<<ORDER
  1561. <!doctype html>
  1562. <html lang="en">
  1563. <head>
  1564. <meta charset="UTF-8" />
  1565. <title>{$taxInvoice}</title>
  1566. <style>
  1567. table {
  1568. border-collapse: collapse;
  1569. }
  1570. table td, table th {
  1571. border: 1px solid #ccc;
  1572. /*padding: 5px 5px;*/
  1573. border-collapse: collapse;
  1574. }
  1575. /*td {*/
  1576. /* padding: 120px;*/
  1577. /*}*/
  1578. .bg {
  1579. background-color: #ccc;
  1580. }
  1581. </style>
  1582. </head>
  1583. <body>
  1584. <div class="content">
  1585. <p style="text-align: left; font-weight: bold; font-size: 30px;"><b>{$taxInvoice}</b><br></p>
  1586. <p style="text-align: left; font-weight: bold; font-size: 22px;"><b>Elken Arabiya General Grading Co.LLC</b><br></p>
  1587. <p style="text-align: left; font-size: 20px;">Shop No.2, Plot 356-1142, Juneirah Street, Umm Suqeim 1, Dubai, UAE<br></p>
  1588. <p style="text-align: left; font-size: 20px;">Shop No.2, Plot 356-1142, Juneirah Street, Umm Suqeim 1, Dubai, UAE<br></p>
  1589. <p style="text-align: left; font-size: 20px;">Phone: +971042296118<br></p>
  1590. <p style="text-align: left; font-size: 20px;">License No: 1314319<br></p>
  1591. <p style="text-align: left; font-size: 20px;">VAT No: 105034822400003<br></p>
  1592. <div>
  1593. <div style="display: block; width: 100%;">
  1594. {$orderBase}
  1595. <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
  1596. <tr>
  1597. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">No</th>
  1598. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productCode}</th>
  1599. <th width="20%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productName}</th>
  1600. <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Quantity</th>
  1601. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Unit Price(AED)</th>
  1602. <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">Unit BV</th>
  1603. <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">Total BV</th>
  1604. <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">Taxable Amount(AED)</th>
  1605. <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">VAT Rate</th>
  1606. <th width="13%" style="font-size: 14px; font-weight: bold; text-align: center;">VAT Amount(AED)</th>
  1607. <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total(AED)</th>
  1608. </tr>
  1609. <tr>
  1610. <td colspan="3">{$total}</td>
  1611. <td style="text-align: right;">{$orderNums}</td>
  1612. <td></td>
  1613. <td style="text-align: right;">{$totalTaxAmount}</td>
  1614. <td style="text-align: right;">{$orderAmount}</td>
  1615. </tr>
  1616. </table>
  1617. </div>
  1618. <div style="width: 100%; margin-top: 50px; height: 30px;">
  1619. <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
  1620. <tr style="border: none;">
  1621. <td width="70%" style="border: none;"></td>
  1622. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$signature}:</td>
  1623. </tr>
  1624. <tr style="border: none;">
  1625. <td width="70%" style="border: none;"></td>
  1626. <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$date}:</td>
  1627. </tr>
  1628. </table>
  1629. </div>
  1630. </div>
  1631. </div>
  1632. </body>
  1633. </html>
  1634. ORDER;
  1635. require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
  1636. $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1637. // 设置打印模式
  1638. $pdf->SetCreator(PDF_CREATOR);
  1639. $pdf->SetAuthor('DaZe');
  1640. $pdf->SetTitle($orderSn);
  1641. $pdf->SetSubject('TCPDF Tutorial');
  1642. $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
  1643. // 是否显示页眉
  1644. $pdf->setPrintHeader(false);
  1645. // 设置页眉字体
  1646. $pdf->setHeaderFont(Array('dejavusans', '', '12'));
  1647. // 页眉距离顶部的距离
  1648. $pdf->SetHeaderMargin('5');
  1649. // 是否显示页脚
  1650. $pdf->setPrintFooter(false);
  1651. // 设置默认等宽字体
  1652. $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  1653. // 设置行高
  1654. $pdf->setCellHeightRatio(1);
  1655. // 设置左、上、右的间距
  1656. $pdf->SetMargins('10', '0', '10');
  1657. // 设置是否自动分页 距离底部多少距离时分页
  1658. $pdf->SetAutoPageBreak(TRUE, '15');
  1659. // 设置图像比例因子
  1660. $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  1661. if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
  1662. require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
  1663. $pdf->setLanguageArray($l);
  1664. }
  1665. $pdf->setFontSubsetting(true);
  1666. $pdf->AddPage();
  1667. // 设置字体
  1668. $pdf->SetFont('stsongstdlight', '', 10, '', true);
  1669. $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
  1670. $image = file_get_contents($image_file);
  1671. $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
  1672. $pdf->writeHTML($context);
  1673. $result = $pdf->Output($realFile, 'F');
  1674. LoggerTool::debug(['result' => $result]);
  1675. $this->_updateFirst($realFile, 1);
  1676. }
  1677. $this->complete();
  1678. return true;
  1679. }
  1680. }