| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985 |
- <?php
- namespace common\libs\export;
- use common\helpers\Cache;
- use common\helpers\Cache as CacheHelper;
- use common\helpers\Date;
- use common\helpers\Form;
- use common\helpers\http\RemoteUploadApi;
- use common\helpers\LoggerTool;
- use common\helpers\Tool;
- use common\helpers\user\Info;
- use common\libs\dataList\DataList;
- use common\models\ApproachOrder;
- use common\models\ApproachOrderGoods;
- use common\models\BaApproachOrder;
- use common\models\BaApproachOrderGoods;
- use common\models\BaOrder;
- use common\models\BaOrderGoods;
- use common\models\BaUser;
- use common\models\Currency;
- use common\models\Export;
- use common\models\Order;
- use common\models\OrderGoods;
- use common\models\Region;
- use common\models\ShopGoods;
- use common\models\User;
- use Yii;
- use yii\base\Exception;
- use yii\base\InvalidConfigException;
- use yii\base\StaticInstanceTrait;
- use yii\base\Component;
- use yii\db\Query;
- class BaseExport extends Component {
- use StaticInstanceTrait;
- public $moduleId;
- /**
- * @var string the model class name. This property must be set.
- */
- public $modelClass;
- /**
- * @var
- */
- public $listModelClass;
- /**
- * @var int
- */
- public $pageSize = 100;
- /**
- * @var int
- */
- public $totalCount = 0;
- /**
- * @var int
- */
- public $offset = 0;
- /**
- * @var int
- */
- public $limit = 100;
- /**
- * csv文件名称
- * @var null
- */
- public $fileName = null;
- /**
- * 保存的基本路径
- * @var null
- */
- public $saveBasePath = null;
- /**
- * 保存路径
- * @var null
- */
- public $savePath = null;
- /**
- * 正在导出的id
- * 来源于exporting_file表
- * @var null
- */
- public $exportId = null;
- /**
- * 操作人的id
- * @var null
- */
- public $userId = null;
- /**
- * 任务id
- * @var null
- */
- public $taskId = null;
- /**
- * 是否完成
- * @var bool
- */
- public $completed = false;
- /**
- * @var array
- */
- public $params = [];
- /**
- * 文件句柄
- * @var null
- */
- private $_fp = null;
- /**
- * 是否上传远程
- * @var bool
- */
- public $isRemote = true;
- /**
- * @var DataList
- */
- private $_listModel;
- public static function factory($taskId) {
- return new self([
- 'taskId' => $taskId
- ]
- );
- }
- /**
- *
- */
- public function init() {
- parent::init();
- $this->isRemote = \Yii::$app->params['isRemoteUpload'];
- }
- /**
- * 生成复杂的路径
- * @return string
- */
- public function pathCreator(...$params) {
- $hash = md5(implode('_', $params));
- $first = substr($hash, 0, 3);
- $second = substr($hash, 3, 2);
- $dir = $first . __DS__ . $second . __DS__;
- return $dir;
- }
- /**
- * 获取文件名
- * @return string|null
- * @throws \Exception
- */
- public function getFileName($ext = '.csv') {
- $this->fileName = date('YmdHis', Date::nowTime()) . random_int(1000, 9999) . $ext;
- return $this->fileName;
- }
- /**
- * 获取保存的路径
- * @return array|null
- */
- public function getSavePath() {
- $this->savePath = $this->pathCreator(date('Ymd', Date::nowTime()));
- return trim((string)$this->savePath, __DS__);
- }
- /**
- * @return bool|string|null
- */
- public function getSaveBasePath() {
- $this->saveBasePath = Yii::getAlias('@backendApi') . __DS__ . 'web' . __DS__ . 'upload' . __DS__ . (isset(\Yii::$app->params['excelLocalDir']) ? \Yii::$app->params['excelLocalDir'] : '');
- return trim((string)$this->saveBasePath, __DS__);
- }
- /**
- * 创建目录(递归创建)
- *
- * @param $dir
- * @return string|false
- */
- public function mkdir($dir) {
- if (!is_dir($dir)) {
- $this->mkdir(dirname($dir));
- if (!mkdir($dir, 0777))
- return false;
- @exec('chown -R www:www /'.$dir);
- @exec('chmod -R 777 /'.$dir);
- }
- return $dir;
- }
- /**
- * @return array|mixed
- */
- public function getParams() {
- $this->params = CacheHelper::getAsyncParams($this->taskId);
-
- // 设置语言
- Yii::$app->language = $this->params['language'] ?? 'en-US';
- Yii::$app->sourceLanguage = Yii::$app->language == 'zh-CN' ? 'en-US' : 'zh-CN';
- return $this->params;
- }
- /**
- * @return mixed|null
- */
- public function getUserId() {
- $this->userId = isset($this->params['userId']) ? $this->params['userId'] : null;
- return $this->userId;
- }
- /**
- * @return |null
- */
- public function getExportId() {
- $this->exportId = isset($this->params['exportId']) ? $this->params['exportId'] : null;
- return $this->userId;
- }
- /**
- * 生成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function generate() {
- $this->getParams();
- if (!$this->params) {
- throw new Exception('无法获取需要的参数');
- }
- $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
- $path = __DS__ . $path;
- $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
- $this->completed = false;
- $this->getExportId();
- $this->getUserId();
- $fileNameUpdated = false;
- $this->_fp = fopen($realFile, 'w');
- @exec('chown -R www:www /'.$realFile);
- @exec('chmod -R 777 /'.$realFile);
- // 获取列表数据及表头
- $this->_listModel = new $this->listModelClass();
- $this->_listModel->isExport = true;
- if(method_exists($this->_listModel, 'getExportHeaders')){
- if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
- $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]);
- }
- $headers = $this->_listModel->getExportHeaders($this->userId);
- fputcsv($this->_fp, $headers);
- unset($headers);
- $this->_updateFirst($realFile, 1);
- } else {
- throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
- }
- $this->_loopWriteData($realFile, $fileNameUpdated);
- $this->complete();
- return true;
- }
- /**
- * 循环写入数据
- * @param $realFile
- * @param $fileNameUpdated
- * @param int $page
- * @param int $counter
- * @return string
- * @throws Exception
- */
- private function _loopWriteData($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
- if(method_exists($this->_listModel, 'getList')){
- $list = $this->_listModel->getList(['condition'=>$this->params['condition'], 'params'=> $this->params['params'] ?? [], 'others'=> $this->params['others'] ?? [], 'page'=>$page, 'pageSize'=>$this->pageSize, 'userId'=>$this->userId]);
- } else {
- throw new Exception($this->listModelClass.'的getList方法不存在');
- }
- if($page >= $list['totalPages']){
- return 'finish';
- }
- if(!empty($list['list'])){
- foreach($list['list'] as $columnData){
- fputcsv($this->_fp, Tool::arrTextConvert($columnData));
- $counter++;
- if ($list['totalCount'] < $counter) {
- // $counter = $list['totalCount'];
- return 'finish';
- }
- $percent = intval(($counter / $list['totalCount']) * 100);
- $this->_updatePercent($percent);
- // if (!$fileNameUpdated) {
- // $this->_updateFirst($realFile, $percent);
- // } else {
- // $this->_updatePercent($percent);
- // }
- // $fileNameUpdated = true;
- unset($percent, $columnData);
- }
- $page++;
- unset($list);
- return $this->_loopWriteData($realFile, $fileNameUpdated, $page, $counter);
- }
- unset($list);
- return 'finish';
- }
- /**
- * 循环写入数据
- */
- private function _loopWriteDataOrder()
- {
- $orderQuery = Order::find()
- ->alias('O')
- ->where($this->params['condition'], $this->params['params'])
- ->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')
- ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- // 订单中间表只查询待支付和支付失败的订单
- $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
- $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
- $orderStandardQuery = ApproachOrder::find()
- ->alias('O')
- ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
- ->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')
- ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- $queryAll = $orderQuery->union($orderStandardQuery, true);
- $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
- $lists = $query->all();
- if(!empty($lists)){
- $regionConfig = Cache::getRegionConfig();
- foreach($lists as $columnData) {
- $CREATE_USER_ID = Info::getUserIdByUserName($columnData['CREATE_USER']);
- $createUserName = Info::getUserRealNameByUserId($CREATE_USER_ID);
- $columnAccept = [
- 'USER_NAME' => $columnData['USER_NAME'],
- 'DEC_USER_NAME' => $columnData['DEC_USER_ID'],
- 'CREATE_USER' => $columnData['CREATE_USER'],
- 'CREATE_USER_NAME' => $createUserName,
- 'SN' => $columnData['SN'],
- 'STATUS' => Tool::paramConvert(\Yii::$app->params['orderStatus'])[$columnData['STATUS']]['label'] ?? '',
- 'SKU_CODE' => $columnData['SKU_CODE'],
- 'GOODS_TITLE' => Tool::mbSignConvert($columnData['GOODS_TITLE']) ,
- 'CONSIGNEE' => $columnData['CONSIGNEE'],
- 'MOBILE' => "\t{$columnData['MOBILE']}",
- 'TEL' => "\t{$columnData['TEL']}",
- 'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
- 'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
- 'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
- 'ADDRESS' => $columnData['ADDRESS'],
- 'PERIOD_NUM' => $columnData['PERIOD_NUM'],
- 'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Repeat Purchase': 'Points'),
- // 'WAREHOUSE' => $columnData['WAREHOUSE'],
- 'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
- 'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
- 'PAY_AT' => $columnData['PAY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['PAY_AT']) : '',
- 'DELIVERY_AT' => $columnData['DELIVERY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']) : '',
- 'BUY_NUMS' => $columnData['BUY_NUMS'],
- 'REAL_PRICE' => $columnData['REAL_PRICE'],
- 'TOTAL_PRICE' => $columnData['REAL_PRICE'] * $columnData['BUY_NUMS'],
- 'REAL_PV' => $columnData['REAL_PV'] * $columnData['BUY_NUMS'],
- 'STANDARD_PRICE' => $columnData['STANDARD_PRICE'] * $columnData['BUY_NUMS'],
- 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'],
- 'TAX_RATE' => $columnData['TAX_RATE'],
- 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
- 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
- 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
- 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
- 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
- 'DELIVERY_STATUS_NAME' => Tool::paramConvert(\Yii::$app->params['deliveryStatus'])[$columnData['DELIVERY_STATUS']]['label'] ?? '',
- 'IS_AUTO' => $columnData['IS_AUTO'] == 1 ? 'Yes' : 'No',
- ];
- fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
- unset($percent, $columnData, $columnAccept);
- }
- unset($list);
- }
- unset($list);
- return 'finish';
- }
- /**
- * 完成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function complete() {
- $this->_updatePercent(100);
- if ($this->completed) {
- return true;
- }
- if ($this->_fp) {
- fclose($this->_fp);
- }
- // 把导出的文件上传至静态文件服务器
- if ($this->isRemote) {
- $realFile = $this->getSaveBasePath() . __DS__ . $this->getSavePath() . __DS__ . $this->getFileName();
- $remoteUploadApi = RemoteUploadApi::instance();
- if ($uploadResult = $remoteUploadApi->upload($realFile)) {
- Export::updateAll(['REMOTE_URL' => $uploadResult['url'], 'IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
- } else {
- $this->_errorHandle();
- throw new Exception('文件远程上传失败');
- }
- // 删除本地临时文件
- unlink($realFile);
- } else {
- Export::updateAll(['IS_EXPORTING' => 0, 'EXPORT_PERCENT' => 100, 'ENDED_AT' => Date::nowTime()], 'ID=:ID', [':ID' => $this->exportId]);
- }
- \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin(100, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
- CacheHelper::deleteAsyncParams($this->taskId);
- $this->completed = true;
- }
- /**
- * @param $message
- */
- private function _errorNotice($message) {
- Yii::$app->swooleAsyncTimer->pushAsyncResultToAdmin($this->userId, $message, false);
- }
- /**
- * 首次更新
- * @param $exportId
- * @param $realName
- */
- private function _updateFirst($realName, $percent) {
- $fileName = str_replace($this->getSaveBasePath() . __DS__, '', $realName);
- Export::updateAll([
- 'FILE_NAME' => str_replace(__DS__, '/', $fileName),
- 'UPDATED_AT' => Date::nowTime(),
- 'EXPORT_PERCENT' => $percent,
- ], 'ID=:ID', [':ID' => $this->exportId]);
- }
- /**
- * 更新百分比
- * @param $exportId
- * @param $percent
- */
- private function _updatePercent($percent) {
- // 把数据写入数据库中
- Export::updateAll(['EXPORT_PERCENT' => $percent], 'ID=:ID', [':ID' => $this->exportId]);
- \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'EXPORT', 'ID' => $this->exportId, 'FIELD' => 'EXPORT_PERCENT']);
- }
- /**
- * 发生错误处理
- * @param $exportId
- */
- private function _errorHandle() {
- Export::updateAll(['IS_EXPORTING' => 0], 'ID=:ID', [':ID' => $this->exportId]);
- }
- /**
- * 导出逻辑
- * @param $filter
- * @param $listName
- * @param null $consoleRouter
- * @throws Exception
- */
- public function exportHandle($filter, $listName, $consoleRouter = null){
- $params = [
- 'moduleId' => $this->moduleId,
- 'listName' => $listName,
- 'action' => $consoleRouter ? $consoleRouter : Yii::$app->controller->id.'/'.Yii::$app->controller->action->id, // 这里这么写,是因为调用的异步路由和同步的控制器和方法是一样的,所以,只要不传默认调和同步一样的异步方法
- 'userId' => Yii::$app->user->id,
- ];
- $this->webToAsync($params,$filter);
- }
- /**
- * 页面到异步的请求
- * @param $params
- * @param array $extend
- * @return bool
- * @throws Exception
- */
- public function webToAsync($params, $extend = []) {
- $default = [
- 'moduleId' => null,
- 'listName' => null,
- 'remark' => null,
- 'action' => null,
- 'userId' => null,
- ];
- $params = Tool::deepParse($params, $default);
- if (!$params['moduleId'] || !$params['listName'] || !$params['action']) {
- throw new Exception('请设置moduleId,listName和action');
- }
- // 把文件对应的相关资料存入数据库中
- $export = new Export();
- $export->EXPORT_NAME = $params['listName'] . '_' . date('Exp_y-m-d H:i:s', Date::nowTime());
- $export->MODULE_NAME = $params['moduleId'];
- $export->REMARK = $params['remark'];
- $export->IS_EXPORTING = 1;
- $export->ADMIN_ID = \Yii::$app->user->id;
- $export->STARTED_AT = Date::nowTime();
- $export->CREATED_AT = Date::nowTime();
- $export->EXPORT_PERCENT = 0;
- $export->ENDED_AT = 0;
- $export->UPDATED_AT = 0;
- if (!$export->save()) {
- throw new Exception(Form::formatErrorsForApi($export->getErrors()));
- }
- $extend = array_merge($extend, [
- 'exportId' => $export->ID,
- 'userId' => $params['userId'],
- 'language' => Yii::$app->language,
- ]);
- // 异步处理添加任务
- $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle($params['action'], $extend);
- if($taskKey === false){
- // 删除刚刚添加的导出数据
- Export::deleteAll(['ID'=>$export->ID]);
- throw new Exception('导出失败,请求异步处理服务器失败');
- }
- return $taskKey;
- }
- /**
- * 生成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function generateOrderExcel() {
- $this->getParams();
- if (!$this->params) {
- throw new Exception('无法获取需要的参数');
- }
- $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
- $path = __DS__ . $path;
- $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
- $this->completed = false;
- $this->getExportId();
- $this->getUserId();
- $fileNameUpdated = false;
- $this->_fp = fopen($realFile, 'w');
- @exec('chown -R www:www /'.$realFile);
- @exec('chmod -R 777 /'.$realFile);
- // 获取列表数据及表头
- $this->_listModel = new $this->listModelClass();
- $this->_listModel->isExport = true;
- if(method_exists($this->_listModel, 'getExportHeaders')){
- if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
- $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
- }
- $headers = $this->_listModel->getExportHeaders($this->userId);
- fputcsv($this->_fp, $headers);
- unset($headers);
- $this->_updateFirst($realFile, 1);
- } else {
- throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
- }
- $this->_loopWriteDataOrder();
- $this->complete();
- return true;
- }
- /**
- * 生成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function generateOrderPDF() {
- $this->getParams();
- if (!$this->params) {
- throw new Exception('无法获取需要的参数');
- }
- $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
- $realFile = $this->mkdir($path) . __DS__ . $this->getFileName('.pdf');
- $this->completed = false;
- $this->getExportId();
- $this->getUserId();
- $fileNameUpdated = false;
- // 获取列表数据及表头
- $this->_listModel = new $this->listModelClass();
- $this->_listModel->isExport = true;
- // 查询订单数据
- // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
- $orderQuery = Order::find()
- ->alias('O')
- ->where($this->params['condition'], $this->params['params'])
- ->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')
- ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- // 订单中间表只查询待支付和支付失败的订单
- $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
- $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
- $orderStandardQuery = ApproachOrder::find()
- ->alias('O')
- ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
- ->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')
- ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- $queryAll = $orderQuery->union($orderStandardQuery, true);
- $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
- $oderList = $query->all();
- if ($oderList) {
- $userId = '';
- $userName = '';
- $address = '';
- $mobile = '';
- $orderAt = '';
- $orderDetails = '';
- $orderSn = '';
- $orderAmount = 0; // 合计总额
- $orderNums = 0; // 合计总数
- $totalTaxAmount = 0; // 合计税额
- $totalAmount = 0;
- foreach ($oderList as $key => $value) {
- $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
- $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
- $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
- $userId = $value['USER_NAME'];
- $userName = $value['REAL_NAME'];
- $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
- $mobile = $value['MOBILE'];
- $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
- $orderSn = $value['SN'];
- // 总价
- $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
- $orderAmount += $totalAmount;
- $orderNums += $value['BUY_NUMS'];
- // 税额
- $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
- $totalTaxAmount += $taxAmount;
- $taxAmount = Tool::formatAmount($taxAmount);
- $totalAmount = Tool::formatAmount($totalAmount);
- // 订单详情
- $orderDetails .= <<<EOT
- <tr>
- <td>{$value['SKU_CODE']}</td>
- <td>{$value['GOODS_TITLE']}</td>
- <td style="text-align: right;">{$value['REAL_PRICE']}</td>
- <td>{$value['BUY_NUMS']}</td>
- <td style="text-align: right;">{$value['TAX_RATE']}</td>
- <td style="text-align: right;">{$taxAmount}</td>
- <td style="text-align: right;">{$totalAmount}</td>
- </tr>
- EOT;
- }
- $memberCode = Yii::t('app', 'memberCode');
- $memberName = Yii::t('app', 'memberName');
- $memberAddress = Yii::t('app', 'memberAddress');
- $memberPhone = Yii::t('app', 'memberPhone');
- $orderCode = Yii::t('app', 'orderCode');
- $orderDetail = Yii::t('app', 'orderDetail');
- $productCode = Yii::t('app', 'productCode');
- $productName = Yii::t('app', 'productName');
- $productPrice = Yii::t('app', 'productPrice');
- $quantity = Yii::t('app', 'qty');
- $taxRate = Yii::t('app', 'taxRate');
- $totalTax = Yii::t('app', 'totalTax');
- $totalAmount = Yii::t('app', 'totalAmount');
- $total = Yii::t('app', 'total');
- $signature = Yii::t('app', 'signature');
- $date = Yii::t('app', 'date');
- $createAt = Yii::t('app', 'createAt');
- // 订单基本信息
- $orderBase = <<<ORDER
- <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberCode}</td>
- <td width="70%">{$userId}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberName}</td>
- <td width="70%">{$userName}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberAddress}</td>
- <td width="70%">{$address}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberPhone}</td>
- <td width="70%">{$mobile}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$orderCode}</td>
- <td width="70%">{$orderSn}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$createAt}</td>
- <td width="70%">{$orderAt}</td>
- </tr>
- <tr>
- <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">{$orderDetail}</td>
- <td class="bg"></td>
- </tr>
- </table>
- ORDER;
- $l['a_meta_charset'] = 'UTF-8';
- $l['a_meta_dir'] = 'ltr';
- $l['a_meta_language'] = 'zh';
- $l['w_page'] = '页面';
- $orderAmount = Tool::formatAmount($orderAmount);
- $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
- $context = <<<ORDER
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <title>{$orderDetail}</title>
- <style>
- table {
- border-collapse: collapse;
- }
- table td, table th {
- border: 1px solid #ccc;
- /*padding: 5px 5px;*/
- border-collapse: collapse;
- }
- /*td {*/
- /* padding: 120px;*/
- /*}*/
- .bg {
- background-color: #ccc;
- }
- </style>
- </head>
- <body>
- <div class="content">
- <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>{$orderDetail}</b><br></p>
- <div>
- <div style="display: block; width: 100%;">
- {$orderBase}
-
- <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
- <tr>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productCode}</th>
- <th width="20%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productName}</th>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productPrice}</th>
- <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">{$quantity}</th>
- <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">{$taxRate}</th>
- <th width="13%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalTax}</th>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalAmount}</th>
- </tr>
- {$orderDetails}
- <tr>
- <td colspan="3">{$total}</td>
- <td style="text-align: right;">{$orderNums}</td>
- <td></td>
- <td style="text-align: right;">{$totalTaxAmount}</td>
- <td style="text-align: right;">{$orderAmount}</td>
- </tr>
- </table>
- </div>
-
- <div style="width: 100%; margin-top: 50px; height: 30px;">
- <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
- <tr style="border: none;">
- <td width="70%" style="border: none;"></td>
- <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$signature}:</td>
- </tr>
- <tr style="border: none;">
- <td width="70%" style="border: none;"></td>
- <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$date}:</td>
- </tr>
- </table>
- </div>
- </div>
- </div>
- </body>
- </html>
- ORDER;
- require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
- $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
- // 设置打印模式
- $pdf->SetCreator(PDF_CREATOR);
- $pdf->SetAuthor('DaZe');
- $pdf->SetTitle($orderSn);
- $pdf->SetSubject('TCPDF Tutorial');
- $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
- // 是否显示页眉
- $pdf->setPrintHeader(false);
- // 设置页眉字体
- $pdf->setHeaderFont(Array('dejavusans', '', '12'));
- // 页眉距离顶部的距离
- $pdf->SetHeaderMargin('5');
- // 是否显示页脚
- $pdf->setPrintFooter(false);
- // 设置默认等宽字体
- $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
- // 设置行高
- $pdf->setCellHeightRatio(1);
- // 设置左、上、右的间距
- $pdf->SetMargins('10', '0', '10');
- // 设置是否自动分页 距离底部多少距离时分页
- $pdf->SetAutoPageBreak(TRUE, '15');
- // 设置图像比例因子
- $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
- if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
- require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
- $pdf->setLanguageArray($l);
- }
- $pdf->setFontSubsetting(true);
- $pdf->AddPage();
- // 设置字体
- $pdf->SetFont('stsongstdlight', '', 10, '', true);
- // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
- // if (!file_exists($image_file)) {
- // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
- // }
- $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
- $image = file_get_contents($image_file);
- $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
- $pdf->writeHTML($context);
- $result = $pdf->Output($realFile, 'F');
- LoggerTool::debug(['result' => $result]);
- $this->_updateFirst($realFile, 1);
- }
- $this->complete();
- return true;
- }
- /**
- * 生成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function generateDecOrderPDF() {
- $this->getParams();
- if (!$this->params) {
- throw new Exception('无法获取需要的参数');
- }
- $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
- $realFile = $path . __DS__ . $this->getFileName('.pdf');
- $this->completed = false;
- $this->getExportId();
- $this->getUserId();
- $fileNameUpdated = false;
- // 获取列表数据及表头
- $this->_listModel = new $this->listModelClass();
- $this->_listModel->isExport = true;
- // 查询订单数据
- // $oderList = $this->_loopWriteDataPDF($realFile, $fileNameUpdated);
- $orderQuery = Order::find()
- ->alias('O')
- ->where($this->params['condition'], $this->params['params'])
- ->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')
- ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', OrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- // 订单中间表只查询待支付和支付失败的订单
- $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
- $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
- $orderStandardQuery = ApproachOrder::find()
- ->alias('O')
- ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
- ->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')
- ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', ApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- $queryAll = $orderQuery->union($orderStandardQuery, true);
- $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
- $oderList = $query->all();
- if ($oderList) {
- $userId = '';
- $userName = '';
- $address = '';
- $mobile = '';
- $orderAt = '';
- $orderDetails = '';
- $orderSn = '';
- $orderAmount = 0; // 合计总额
- $orderNums = 0; // 合计总数
- $totalTaxAmount = 0; // 合计税额
- $totalAmount = 0;
- foreach ($oderList as $key => $value) {
- $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
- $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
- $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
- $userId = $value['USER_NAME'];
- $userName = $value['REAL_NAME'];
- $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
- $mobile = $value['MOBILE'];
- $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
- $orderSn = $value['SN'];
- // 总价
- $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
- $orderAmount += $totalAmount;
- $orderNums += $value['BUY_NUMS'];
- // 税额
- $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
- $totalTaxAmount += $taxAmount;
- $taxAmount = Tool::formatAmount($taxAmount);
- $totalAmount = Tool::formatAmount($totalAmount);
- // 订单详情
- $orderDetails .= <<<EOT
- <tr>
- <td>{$value['SKU_CODE']}</td>
- <td>{$value['GOODS_TITLE']}</td>
- <td style="text-align: right;">{$value['REAL_PRICE']}</td>
- <td>{$value['BUY_NUMS']}</td>
- <td style="text-align: right;">{$value['TAX_RATE']}</td>
- <td style="text-align: right;">{$taxAmount}</td>
- <td style="text-align: right;">{$totalAmount}</td>
- </tr>
- EOT;
- }
- $memberCode = Yii::t('app', 'memberCode');
- $memberName = Yii::t('app', 'memberName');
- $memberAddress = Yii::t('app', 'memberAddress');
- $memberPhone = Yii::t('app', 'memberPhone');
- $orderCode = Yii::t('app', 'orderCode');
- $orderDetail = Yii::t('app', 'orderDetail');
- $productCode = Yii::t('app', 'productCode');
- $productName = Yii::t('app', 'productName');
- $productPrice = Yii::t('app', 'productPrice');
- $quantity = Yii::t('app', 'qty');
- $taxRate = Yii::t('app', 'taxRate');
- $totalTax = Yii::t('app', 'totalTax');
- $totalAmount = Yii::t('app', 'totalAmount');
- $total = Yii::t('app', 'total');
- $signature = Yii::t('app', 'signature');
- $date = Yii::t('app', 'date');
- $createAt = Yii::t('app', 'createAt');
- // 订单基本信息
- $orderBase = <<<ORDER
- <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberCode}</td>
- <td width="70%">{$userId}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberName}</td>
- <td width="70%">{$userName}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberAddress}</td>
- <td width="70%">{$address}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$memberPhone}</td>
- <td width="70%">{$mobile}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$orderCode}</td>
- <td width="70%">{$orderSn}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">{$createAt}</td>
- <td width="70%">{$orderAt}</td>
- </tr>
- <tr>
- <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">{$orderDetail}</td>
- <td class="bg"></td>
- </tr>
- </table>
- ORDER;
- $l['a_meta_charset'] = 'UTF-8';
- $l['a_meta_dir'] = 'ltr';
- $l['a_meta_language'] = 'zh';
- $l['w_page'] = '页面';
- $orderAmount = sprintf('%.2f', $orderAmount);
- $totalTaxAmount = sprintf('%.2f', $totalTaxAmount);
- $context = <<<ORDER
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <title>{$orderDetail}</title>
- <style>
- table {
- border-collapse: collapse;
- }
- table td, table th {
- border: 1px solid #ccc;
- /*padding: 5px 5px;*/
- border-collapse: collapse;
- }
- /*td {*/
- /* padding: 120px;*/
- /*}*/
- .bg {
- background-color: #ccc;
- }
- </style>
- </head>
- <body>
- <div class="content">
- <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>{$orderDetail}</b><br></p>
- <div>
- <div style="display: block; width: 100%;">
- {$orderBase}
-
- <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
- <tr>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productCode}</th>
- <th width="20%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productName}</th>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$productPrice}</th>
- <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">{$quantity}</th>
- <th width="12%" style="font-size: 14px; font-weight: bold; text-align: center;">{$taxRate}</th>
- <th width="13%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalTax}</th>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">{$totalAmount}</th>
- </tr>
- {$orderDetails}
- <tr>
- <td colspan="3">{$total}</td>
- <td style="text-align: right;">{$orderNums}</td>
- <td></td>
- <td style="text-align: right;">{$totalTaxAmount}</td>
- <td style="text-align: right;">{$orderAmount}</td>
- </tr>
- </table>
- </div>
-
- <div style="width: 100%; margin-top: 50px; height: 30px;">
- <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
- <tr style="border: none;">
- <td width="70%" style="border: none;"></td>
- <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$signature}:</td>
- </tr>
- <tr style="border: none;">
- <td width="70%" style="border: none;"></td>
- <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">{$date}:</td>
- </tr>
- </table>
- </div>
- </div>
- </div>
- </body>
- </html>
- ORDER;
- require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
- $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
- // 设置打印模式
- $pdf->SetCreator(PDF_CREATOR);
- $pdf->SetAuthor('DaZe');
- $pdf->SetTitle($orderSn);
- $pdf->SetSubject('TCPDF Tutorial');
- $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
- // 是否显示页眉
- $pdf->setPrintHeader(false);
- // 设置页眉字体
- $pdf->setHeaderFont(Array('dejavusans', '', '12'));
- // 页眉距离顶部的距离
- $pdf->SetHeaderMargin('5');
- // 是否显示页脚
- $pdf->setPrintFooter(false);
- // 设置默认等宽字体
- $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
- // 设置行高
- $pdf->setCellHeightRatio(1);
- // 设置左、上、右的间距
- $pdf->SetMargins('10', '10', '10');
- // 设置是否自动分页 距离底部多少距离时分页
- $pdf->SetAutoPageBreak(TRUE, '15');
- // 设置图像比例因子
- $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
- if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
- require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
- $pdf->setLanguageArray($l);
- }
- $pdf->setFontSubsetting(true);
- $pdf->AddPage();
- // 设置字体
- $pdf->SetFont('stsongstdlight', '', 10, '', true);
- $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
- // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
- // if (!file_exists($image_file)) {
- // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
- // }
- $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
- $image = file_get_contents($image_file);
- $pdf->Image('@' . $image, 165, 5, 20, 10, 'JPG');
- $pdf->writeHTML($context);
- $pdf->Output($realFile, 'F');
- $this->_updateFirst($realFile, 1);
- }
- $this->complete();
- return true;
- }
- /**
- * 循环写入数据
- * @param $realFile
- * @param $fileNameUpdated
- * @param int $page
- * @param int $counter
- * @return array
- * @throws Exception
- */
- private function _loopWriteDataPDF($realFile, &$fileNameUpdated, $page = 0, $counter = 0){
- if(method_exists($this->_listModel, 'getList')){
- $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]);
- } else {
- throw new Exception($this->listModelClass.'的getList方法不存在');
- }
- return $list['list'];
- }
- /**
- * 生成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function generateBaOrderExcel() {
- $this->getParams();
- if (!$this->params) {
- throw new Exception('无法获取需要的参数');
- }
- $path = $this->getSaveBasePath() . __DS__ . $this->getSavePath();
- $path = __DS__ . $path;
- $realFile = $this->mkdir($path) . __DS__ . $this->getFileName();
- $this->completed = false;
- $this->getExportId();
- $this->getUserId();
- $this->_fp = fopen($realFile, 'w');
- @exec('chown -R www:www /'.$realFile);
- @exec('chmod -R 777 /'.$realFile);
- // 获取列表数据及表头
- $this->_listModel = new $this->listModelClass();
- $this->_listModel->isExport = true;
- if(method_exists($this->_listModel, 'getExportHeaders')){
- if(method_exists($this->_listModel, 'exportPrepare')) {//导出数据提前设置参数
- $this->_listModel->exportPrepare(['condition' => $this->params['condition'], 'params' => $this->params['params'], 'others' => $this->params['others'] ?? [], 'page' => 0, 'pageSize' => 100000, 'userId' => $this->userId]);
- }
- $headers = $this->_listModel->getExportHeaders($this->userId);
- fputcsv($this->_fp, $headers);
- unset($headers);
- $this->_updateFirst($realFile, 1);
- } else {
- throw new Exception($this->listModelClass.'的getExportHeaders方法不存在');
- }
- $this->_loopWriteDataBaOrder();
- $this->complete();
- return true;
- }
- /**
- * 循环写入数据
- */
- private function _loopWriteDataBaOrder()
- {
- $orderQuery = BaOrder::find()
- ->alias('O')
- ->where($this->params['condition'], $this->params['params'])
- ->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')
- ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- // 订单中间表只查询待支付和支付失败的订单
- $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
- $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
- $orderStandardQuery = BaApproachOrder::find()
- ->alias('O')
- ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
- ->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')
- ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- $queryAll = $orderQuery->union($orderStandardQuery, true);
- $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
- $lists = $query->all();
- if(!empty($lists)){
- $regionConfig = Cache::getRegionConfig();
- foreach($lists as $columnData) {
- $CREATE_USER_ID = Info::getBaUserIdByUserName($columnData['CREATE_USER']);
- $createUserName = Info::getBaUserRealNameByUserId($CREATE_USER_ID);
- $decUserName = Info::getBaUserNameByUserId($columnData['DEC_ID']);
- $columnAccept = [
- 'USER_NAME' => $columnData['USER_NAME'],
- 'DEC_USER_NAME' => $decUserName,
- 'CREATE_USER' => $columnData['CREATE_USER'],
- 'CREATE_USER_NAME' => $createUserName,
- 'SN' => $columnData['SN'],
- 'STATUS' => Tool::paramConvert(\Yii::$app->params['orderStatus'])[$columnData['STATUS']]['label'] ?? '',
- 'SKU_CODE' => $columnData['SKU_CODE'],
- 'GOODS_TITLE' => $columnData['GOODS_TITLE'],
- 'BUY_NUMS' => $columnData['BUY_NUMS'],
- 'CONSIGNEE' => $columnData['CONSIGNEE'],
- 'MOBILE' => "\t{$columnData['MOBILE']}",
- 'TEL' => "\t{$columnData['TEL']}",
- 'PROVINCE' => $regionConfig[$columnData['PROVINCE']]['REGION_NAME'] ?? '',
- 'CITY' => $regionConfig[$columnData['CITY']]['REGION_NAME'] ?? '',
- 'COUNTY' => $regionConfig[$columnData['COUNTY']]['REGION_NAME'] ?? '',
- 'ADDRESS' => $columnData['ADDRESS'],
- 'PERIOD_NUM' => $columnData['PERIOD_NUM'],
- 'ORDER_TYPE' => ($columnData['ORDER_TYPE'] == 'ZC') ? 'Welcome pack' : (in_array($columnData['PAY_TYPE'], ['cash', 'pay_stack']) ? 'Reselling': 'Points'),
- 'CREATED_AT' => Date('Y-m-d H:i:s', $columnData['CREATED_AT']),
- 'PAY_TYPE' => ShopGoods::payTypes()[$columnData['PAY_TYPE']]['name'] ?? ShopGoods::payTypes()['cash']['name'],
- 'PAY_AT' => $columnData['PAY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['PAY_AT']) : '',
- 'DELIVERY_AT' => $columnData['DELIVERY_AT'] > 0 ? Date('Y-m-d H:i:s', $columnData['DELIVERY_AT']) : '',
- 'REAL_PRICE' => $columnData['REAL_PRICE'] ?? 0,
- 'REAL_PV' => $columnData['REAL_PV'] ?? 0,
- 'PAY_FREIGHT' => $columnData['PAY_FREIGHT'] ?? 0,
- 'TAX_RATE' => $columnData['TAX_RATE'],
- 'TAX_AMOUNT' => Tool::calculateTax($columnData['REAL_PRICE'], $columnData['TAX_RATE'], $columnData['BUY_NUMS']),
- 'EXPRESS_COMPANY' => $columnData['EXPRESS_COMPANY'],
- 'ORDER_TRACK_NO' => $columnData['ORDER_TRACK_NO'],
- 'EXPRESS_TYPE' => $columnData['EXPRESS_TYPE'] == 0 ? 'mailing ':' auto pick',
- 'FRONT_REMARK' => $columnData['FRONT_REMARK'],
- 'DELIVERY_STATUS_NAME' => Tool::paramConvert(\Yii::$app->params['deliveryStatus'])[$columnData['DELIVERY_STATUS']]['label'] ?? '',
- ];
-
- fputcsv($this->_fp, Tool::arrTextConvert($columnAccept));
- unset($percent, $columnData, $columnAccept);
- }
- unset($list);
- }
- unset($list);
- return 'finish';
- }
- /**
- * 生成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function generateBaOrderPDF()
- {
- $this->getParams();
- if (!$this->params) {
- throw new Exception('无法获取需要的参数');
- }
- $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
- $realFile = $path . __DS__ . $this->getFileName('.pdf');
- $this->completed = false;
- $this->getExportId();
- $this->getUserId();
- $fileNameUpdated = false;
- // 获取列表数据及表头
- $this->_listModel = new $this->listModelClass();
- $this->_listModel->isExport = true;
- // 查询订单数据
- $orderQuery = BaOrder::find()
- ->alias('O')
- ->where($this->params['condition'], $this->params['params'])
- ->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')
- ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', BaOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- // 订单中间表只查询待支付和支付失败的订单
- $this->params['params'][':NOT_PAID'] = \Yii::$app->params['orderStatus']['notPaid']['value']; // 待支付
- $this->params['params'][':FAIL_PAID'] = \Yii::$app->params['orderStatus']['failPaid']['value']; // 支付失败
- $orderStandardQuery = BaApproachOrder::find()
- ->alias('O')
- ->where($this->params['condition'] . ' AND (O.STATUS = :NOT_PAID OR O.STATUS = :FAIL_PAID)', $this->params['params'])
- ->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')
- ->join('LEFT JOIN', BaUser::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', BaApproachOrderGoods::tableName() . ' AS OG', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->orderBy('O.CREATED_AT DESC');
- $queryAll = $orderQuery->union($orderStandardQuery, true);
- $query = (new Query())->from(['Q' => $queryAll])->select('Q.*')->distinct()->orderBy(['CREATED_AT' => SORT_DESC]);
- $oderList = $query->all();
- if ($oderList) {
- $userId = '';
- $userName = '';
- $address = '';
- $mobile = '';
- $orderAt = '';
- $orderDetails = '';
- $orderSn = '';
- $orderAmount = 0; // 合计总额
- $orderNums = 0; // 合计总数
- $totalTaxAmount = 0; // 合计税额
- $totalAmount = 0;
- foreach ($oderList as $key => $value) {
- $provinceName = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
- $cityName = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
- $countyName = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
- $userId = $value['USER_NAME'];
- $userName = $value['REAL_NAME'];
- $address = $provinceName . $cityName . $countyName . $value['ADDRESS'];
- $mobile = $value['MOBILE'];
- $orderAt = Date::convert($value['CREATED_AT'],'Y-m-d H:i:s');
- $orderSn = $value['SN'];
- // 总价
- $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
- $orderAmount += $totalAmount;
- $orderNums += $value['BUY_NUMS'];
- // 税额
- $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
- $totalTaxAmount += $taxAmount;
- $taxAmount = Tool::formatAmount($taxAmount);
- $totalAmount = Tool::formatAmount($totalAmount);
- // 订单详情
- $orderDetails .= <<<EOT
- <tr>
- <td>{$value['SKU_CODE']}</td>
- <td>{$value['GOODS_TITLE']}</td>
- <td style="text-align: right;">{$value['REAL_PRICE']}</td>
- <td>{$value['BUY_NUMS']}</td>
- <td style="text-align: right;">{$value['TAX_RATE']}</td>
- <td style="text-align: right;">{$taxAmount}</td>
- <td style="text-align: right;">{$totalAmount}</td>
- </tr>
- EOT;
- }
- // 订单基本信息
- $orderBase = <<<ORDER
- <table border="1" style="table-layout: fixed; padding: 10px 20px;" width="100%">
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Code</td>
- <td width="70%">{$userId}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Name</td>
- <td width="70%">{$userName}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Address</td>
- <td width="70%">{$address}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Member Phone</td>
- <td width="70%">{$mobile}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Order Code</td>
- <td width="70%">{$orderSn}</td>
- </tr>
- <tr>
- <td width="30%" style="font-weight: bold; text-align: center; font-size: 14px;">Creation Time</td>
- <td width="70%">{$orderAt}</td>
- </tr>
- <tr>
- <td class="bg" style="font-weight: bold; font-size: 14px; text-align: center;">Order Detail</td>
- <td class="bg"></td>
- </tr>
- </table>
- ORDER;
- $l['a_meta_charset'] = 'UTF-8';
- $l['a_meta_dir'] = 'ltr';
- $l['a_meta_language'] = 'zh';
- $l['w_page'] = '页面';
- $orderAmount = Tool::formatAmount($orderAmount);
- $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
- $context = <<<ORDER
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <title>Order detail</title>
- <style>
- table {
- border-collapse: collapse;
- }
- table td, table th {
- border: 1px solid #ccc;
- padding: 5px 5px;
- border-collapse: collapse;
- }
- /*td {*/
- /* padding: 120px;*/
- /*}*/
- .bg {
- background-color: #ccc;
- }
- </style>
- </head>
- <body>
- <div class="content">
- <p style="text-align: center; font-weight: bold; font-size: 22px;"><b>Order detail</b><br></p>
- <div>
- <div style="display: block; width: 100%;">
- {$orderBase}
-
- <table border="1" width="100%" style="padding: 10px 5px; text-align: center;">
- <tr>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Code</th>
- <th width="25%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Name</th>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Product Price</th>
- <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Qty</th>
- <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax Rate</th>
- <th width="10%" style="font-size: 14px; font-weight: bold; text-align: center;">Tax</th>
- <th width="15%" style="font-size: 14px; font-weight: bold; text-align: center;">Total Amount</th>
- </tr>
- {$orderDetails}
- <tr>
- <td colspan="3">Total</td>
- <td>{$orderNums}</td>
- <td></td>
- <td style="text-align: right;">{$totalTaxAmount}</td>
- <td style="text-align: right;">{$orderAmount}</td>
- </tr>
- </table>
- </div>
-
- <div style="width: 100%; margin-top: 50px; height: 30px;">
- <table width="100%" style="border: none; padding: 10px 20px; text-align: center;">
- <tr style="border: none;">
- <td width="70%" style="border: none;"></td>
- <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Signature:</td>
- </tr>
- <tr style="border: none;">
- <td width="70%" style="border: none;"></td>
- <td width="30%" style="font-weight: bold; text-align: left; font-size: 14px; border: none;">Date:</td>
- </tr>
- </table>
- </div>
- </div>
- </div>
- </body>
- </html>
- ORDER;
- require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
- $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
- // 设置打印模式
- $pdf->SetCreator(PDF_CREATOR);
- $pdf->SetAuthor('DaZe');
- $pdf->SetTitle($orderSn);
- $pdf->SetSubject('TCPDF Tutorial');
- $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
- // 是否显示页眉
- $pdf->setPrintHeader(false);
- // 设置页眉字体
- $pdf->setHeaderFont(Array('dejavusans', '', '12'));
- // 页眉距离顶部的距离
- $pdf->SetHeaderMargin('5');
- // 是否显示页脚
- $pdf->setPrintFooter(false);
- // 设置默认等宽字体
- $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
- // 设置行高
- $pdf->setCellHeightRatio(1);
- // 设置左、上、右的间距
- $pdf->SetMargins('10', '0', '10');
- // 设置是否自动分页 距离底部多少距离时分页
- $pdf->SetAutoPageBreak(TRUE, '15');
- // 设置图像比例因子
- $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
- if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
- require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
- $pdf->setLanguageArray($l);
- }
- $pdf->setFontSubsetting(true);
- $pdf->AddPage();
- // 设置字体
- $pdf->SetFont('stsongstdlight', '', 10, '', true);
- // $image_file = \Yii::$app->basePath . '/../frontendEle/src/static/img/ngds-logo.jpg';
- // if (!file_exists($image_file)) {
- // $image_file = \Yii::$app->runtimePath . '/../common/uploads/ngds-logo.jpg';
- // }
- $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
- $image = file_get_contents($image_file);
- $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
- $pdf->writeHTML($context);
- $pdf->Output($realFile, 'F');
- $this->_updateFirst($realFile, 1);
- }
- $this->complete();
- return true;
- }
- /**
- * 生成
- * @return bool
- * @throws Exception
- * @throws InvalidConfigException
- * @throws \yii\httpclient\Exception
- */
- public function actionOrderInvoiceExport() {
- $this->getParams();
- if (!$this->params) {
- throw new Exception('无法获取需要的参数');
- }
- $path = __DS__ . $this->getSaveBasePath() . __DS__ . $this->getSavePath();
- $realFile = $this->mkdir($path) . __DS__ . $this->getFileName('.pdf');
- $this->completed = false;
- $this->getExportId();
- $this->getUserId();
- $fileNameUpdated = false;
- // 获取列表数据及表头
- $this->_listModel = new $this->listModelClass();
- $this->_listModel->isExport = true;
- // 查询订单数据
- // 使用新的查询对象,禁用查询缓存,确保获取最新数据
- $query = OrderGoods::find()
- ->alias('OG')
- ->where($this->params['condition'], $this->params['params'])
- ->select('OG.ID AS AID,O.*,U.REAL_NAME,U.DEC_ID,SG.CATEGORY_TYPE,OG.REAL_PRICE,OG.TAX_RATE,OG.BUY_NUMS,OG.SKU_CODE,OG.GOODS_TITLE,OG.REAL_PV')
- ->join('LEFT JOIN', ORDER::tableName() . ' AS O', 'OG.ORDER_SN=O.SN')
- ->join('LEFT JOIN', User::tableName() . ' AS U', 'U.ID=O.USER_ID')
- ->join('LEFT JOIN', ShopGoods::tableName() . ' AS SG', 'SG.ID=OG.GOODS_ID')
- ->asArray()
- ->noCache(); // 禁用查询缓存
- // 添加详细的调试信息
- $rawSql = $query->createCommand()->getRawSql();
- $oderList = $query->all();
-
- // 同时使用原生SQL查询进行对比测试
- $nativeConnection = Yii::$app->db;
- $nativeQuery = "SELECT
- `OG`.`ID` AS `AID`,
- `O`.*,
- `U`.`REAL_NAME`,
- `U`.`DEC_ID`,
- `SG`.`CATEGORY_TYPE`,
- `OG`.`REAL_PRICE`,
- `OG`.`TAX_RATE`,
- `OG`.`BUY_NUMS`,
- `OG`.`SKU_CODE`,
- `OG`.`GOODS_TITLE`,
- `OG`.`REAL_PV`
- FROM
- `AR_ORDER_GOODS` `OG`
- LEFT JOIN `AR_ORDER` `O` ON OG.ORDER_SN = O.SN
- LEFT JOIN `AR_USER` `U` ON U.ID = O.USER_ID
- LEFT JOIN `AR_SHOP_GOODS` `SG` ON SG.ID = OG.GOODS_ID
- WHERE
- O.IS_DELETE = 0
- AND O.SN = 'OS202511087870502295'
- ORDER BY
- `O`.`CREATED_AT` DESC";
- $nativeResults = $nativeConnection->createCommand($nativeQuery)->queryAll();
-
- Yii::info('原生SQL查询结果数量: ' . count($nativeResults), 'export_debug');
- Yii::info('原生SQL查询结果: ' . json_encode($nativeResults), 'export_debug');
-
- // 如果原生查询有结果但Yii查询没有,使用原生查询结果
- if(count($nativeResults) > 0 && count($oderList) < count($nativeResults)) {
- Yii::warning('检测到查询结果不匹配,使用原生SQL查询结果', 'export_debug');
- $oderList = $nativeResults;
- }
-
- LoggerTool::debug([
- 'sql' => $rawSql,
- 'condition' => $this->params['condition'],
- 'params' => $this->params,
- 'orderListCount' => count($oderList),
- 'orderList' => $oderList,
- 'fullParams' => $this->params
- ]);
-
- // 检查是否有查询缓存影响
- Yii::info('查询结果数量: ' . count($oderList), 'export_debug');
- Yii::info('完整SQL: ' . $rawSql, 'export_debug');
- Yii::info('查询条件: ' . json_encode($this->params['condition']), 'export_debug');
- Yii::info('查询参数: ' . json_encode($this->params['params']), 'export_debug');
- if ($oderList) {
- $userId = '';
- $userName = '';
- $address = '';
- $mobile = $oderList[0]['MOBILE'];
- $orderAt = Date::convert($oderList[0]['CREATED_AT'],'Y/m/d');
- $orderDetails = '';
- $orderSn = $oderList[0]['SN'];;
- $orderAmount = 0; // 合计总额
- $orderNums = 0; // 合计总数
- $totalTaxAmount = 0; // 合计税额
- $totalAmount = 0;
- $paymentStatus = 'Paid'; // 支付状态
- $invoiceRemark = $oderList[0]['INVOICE_REMARK'];
- $paymentMethod = $oderList[0]['PAY_TYPE']; // 支付方式
- $currency = Currency::findOne($oderList[0]['CURRENCY_ID'])['CODE'] ?? '';;
- $invoiceNo = $oderList[0]['INVOICE_NO'];
- $provinceName = $oderList[0]['PROVINCE'] ? Region::getCnName($oderList[0]['PROVINCE']) : '';
- $cityName = $oderList[0]['CITY'] ? Region::getCnName($oderList[0]['CITY']) : '';
- $countyName = $oderList[0]['COUNTY'] ? Region::getCnName($oderList[0]['COUNTY']) : '';
- $address = $provinceName . $cityName . $countyName . $oderList[0]['ADDRESS'];
- $paymentMethod = $oderList[0]['PAY_TYPE'] ?? 'Cash';
- $paymentStatus = \Yii::$app->params['orderStatus'][$oderList[0]['STATUS']]['label'] ?? 'Paid';
- $orderTotalBv = 0;
- $orderTotalTaxAmount = 0;
- $orderTotalAmount = 0;
- $orderTotal = 0;
- $orderTotalQuantity = count($oderList);
- $no = 0;
- foreach ($oderList as $key => $value) {
- $no += 1;
- $userId = $value['USER_NAME'];
- $userName = $value['REAL_NAME'];
- // 总价
- $totalAmount = $value['BUY_NUMS'] * $value['REAL_PRICE'];
- $orderAmount += $totalAmount;
- $orderNums += $value['BUY_NUMS'];
- // 税额
- $taxAmount = Tool::calculateTax($value['REAL_PRICE'], $value['TAX_RATE'], $value['BUY_NUMS']);
- $totalTaxAmount += $taxAmount;
- $totalBv = $value['BUY_NUMS'] * $value['REAL_PV'];
- $orderTotalBv += $totalBv;
- $orderTotalTaxAmount += $taxAmount;
- $orderTotalAmount += $totalAmount - $taxAmount;
- $orderTotal += $totalAmount;
- $totalBvFormat = Tool::formatAmount($totalBv);
- $taxableAmountFormat =Tool::formatAmount($taxAmount);
- $vatAmountFormat = Tool::formatAmount($totalAmount - $taxAmount);
- $totalFormat = Tool::formatAmount($totalAmount);
- $vatRateFormat = Tool::formatAmount($value['TAX_RATE']) . '%';
- $unitPriceFormat = Tool::formatAmount($value['REAL_PRICE']);
- $unitBvFormat = Tool::formatAmount($value['REAL_PV']);
- // 订单详情
- $orderDetails .= <<<EOT
- <tr style="text-align: left; padding: 10px 5px; font-weight: normal; font-size: 12px; width: 100%;">
- <td style="width: 30px;">{$no}</td>
- <td>{$value['SKU_CODE']}</td>
- <td>{$value['GOODS_TITLE']}</td>
- <td>{$value['BUY_NUMS']}</td>
- <td>{$unitPriceFormat}</td>
- <td>{$unitBvFormat}</td>
- <td>{$totalBvFormat}</td>
- <td>{$taxableAmountFormat}</td>
- <td>{$vatRateFormat}</td>
- <td>{$vatAmountFormat}</td>
- <td>{$totalFormat}</td>
- </tr>
- EOT;
- }
- $memberCode = Yii::t('app', 'memberCode');
- $memberName = Yii::t('app', 'memberName');
- $memberAddress = Yii::t('app', 'memberAddress');
- $memberPhone = Yii::t('app', 'memberPhone');
- $orderCode = Yii::t('app', 'orderCode');
- $taxInvoice = Yii::t('app', 'taxInvoice');
- $productCode = Yii::t('app', 'productCode');
- $productName = Yii::t('app', 'productName');
- $productPrice = Yii::t('app', 'productPrice');
- $quantity = Yii::t('app', 'qty');
- $taxRate = Yii::t('app', 'taxRate');
- $totalTax = Yii::t('app', 'totalTax');
- $totalAmount = Yii::t('app', 'totalAmount');
- $total = Yii::t('app', 'total');
- $signature = Yii::t('app', 'signature');
- $date = Yii::t('app', 'date');
- $createAt = Yii::t('app', 'createAt');
- $l['a_meta_charset'] = 'UTF-8';
- $l['a_meta_dir'] = 'ltr';
- $l['a_meta_language'] = 'zh';
- $l['w_page'] = '页面';
- $orderAmount = Tool::formatAmount($orderAmount);
- $totalTaxAmount = Tool::formatAmount($totalTaxAmount);
- $orderTotalBv = Tool::formatAmount($orderTotalBv);
- $orderTotalTaxAmount = Tool::formatAmount($orderTotalTaxAmount);
- $orderTotalAmount = Tool::formatAmount($orderTotalAmount);
- $orderTotal = Tool::formatAmount($orderTotal);
- $context = <<<ORDER
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <title>{$taxInvoice}</title>
- <style>
- table {
- border-collapse: collapse;
- }
- table td, table th {
- border: 1px solid #ccc;
- border-collapse: collapse;
- }
- .bg {
- background-color: #ccc;
- }
-
- /* 无边框表格样式类 */
- .table-noborder {
- border-collapse: collapse; /* 合并边框(避免残留间隙) */
- border-spacing: 0; /* 清除单元格之间的默认间隙 */
- empty-cells: show; /* 不影响空单元格(可选,避免意外显示) */
- }
- /* 清除 table、th、td 的所有边框 */
- .table-noborder,
- .table-noborder th,
- .table-noborder td {
- border: none !important; /* !important 可选,用于覆盖冲突样式 */
- outline: none; /* 清除可能的默认轮廓(可选) */
- }
- </style>
- </head>
- <body style="line-height: 10px; font-weight: normal; margin-left: 0; margin-right: 0; margin-top: 0; margin-bottom: 0; padding-left: 0; padding-right: 0; padding-top: 0; padding-bottom: 0; line-height: 20px;">
- <div class="content" style="line-height: 10px; font-weight: normal;">
- <p style="text-align: left; font-weight: bold; font-size: 18px;"><b>Tax Invoice</b><br></p>
- <p style="text-align: left; font-weight: bold; font-size: 15px;"><b>Elken Arabiya General Grading Co.LLC</b><br></p>
- <p style="text-align: left; font-size: 13px;">Shop No.2, Plot 356-1142, Juneirah Street, Umm Suqeim 1, Dubai, UAE<br></p>
- <p style="text-align: left; font-size: 13px;">Phone: +971042296118<br></p>
- <p style="text-align: left; font-size: 13px;">License No: 1314319<br></p>
- <p style="text-align: left; font-size: 13px;">VAT No: {$orderSn}<br></p>
-
- <hr />
- <br>
- <br>
- <div style="width: 100%; line-height: 15px; margin-left: 0; margin-right: 0; margin-top: 0; margin-bottom: 0; padding: 0;">
- <table style="table-layout: fixed; margin-left: 0; margin-right: 0; margin-top: 0; margin-bottom: 0; " class="table-noborder" width="100%">
- <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
- <td>
- Bill to
- </td>
- <td>
- Invoice No.: {$invoiceNo}
- </td>
- </tr>
- <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
- <td>
- Name of Distributor: {$userName}
- </td>
- <td>
- Date: {$orderAt}
- </td>
- </tr>
- <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
- <td>
- Member ID: {$userId}
- </td>
- <td>
- Payment status: {$paymentStatus}
- </td>
- </tr>
- <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
- <td colspan="2">
- Address: {$address}
- </td>
- </tr>
- <tr style="text-align: left; font-size: 12px; font-weight: normal; height: 50px; vertical-align: middle;">
- <td colspan="2">
- Contact: {$mobile}
- </td>
- </tr>
- </table>
-
- <br />
- <br />
- <br />
- <table border="1" width="100%">
- <tr style="text-align: left; font-weight: normal; font-size: 12px; width: 100%; padding: 5px 5px;">
- <th style="width: 30px;">No.</th>
- <th>Product Code</th>
- <th>Product Name</th>
- <th>Quantity</th>
- <th>Unit Price({$currency})</th>
- <th>Unit BV</th>
- <th>Total BV</th>
- <th>Taxable Amount({$currency})</th>
- <th>VAT Rate</th>
- <th>VAT Amount({$currency})</th>
- <th>Total({$currency})</th>
- </tr>
- {$orderDetails}
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr><td colspan="11"></td></tr>
- <tr><td colspan="11"></td></tr>
- </table>
-
- <table style="table-layout: fixed;">
- <tr style="text-align: left; font-weight: normal; font-size: 12px;">
- <td class="table-noborder" style="width: 30px;"></td>
- <td style="text-align: left; background-color: lightslategray;" colspan="2">Grand Total</td>
- <td style="text-align: left; background-color: lightslategray;">{$orderTotalQuantity}</td>
- <td style="text-align: left; background-color: lightslategray;"></td>
- <td style="text-align: left; background-color: lightslategray;"></td>
- <td style="text-align: left; background-color: lightslategray;">{$orderTotalBv}</td>
- <td style="text-align: left; background-color: lightslategray;">{$orderTotalTaxAmount}</td>
- <td style="text-align: left; background-color: lightslategray;"></td>
- <td style="text-align: left; background-color: lightslategray;">{$orderTotalAmount}</td>
- <td style="text-align: left; background-color: lightslategray;">{$orderTotal}</td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr>
- <td colspan="11"></td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;">
- <tr style="text-align: left; font-weight: normal; font-size: 12px;">
- <td colspan="7" class="table-noborder"></td>
- <td style="text-align: left; background-color: lightgoldenrodyellow;" colspan="2" >Total Amount</td>
- <td style="text-align: left; background-color: lightgoldenrodyellow;" colspan="2">{$currency}{$orderAmount}</td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr>
- <td colspan="11"></td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr style="text-align: left; font-weight: normal; font-size: 12px;">
- <td colspan="7"></td>
- <td colspan="2">Method:</td>
- <td colspan="2"></td>
- </tr>
- <tr style="text-align: left; font-weight: normal; font-size: 12px;">
- <td colspan="7"></td>
- <td colspan="2" >Paid amount:</td>
- <td colspan="2">{$currency}{$orderAmount}</td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr>
- <td colspan="11"></td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr style="text-align: left; font-weight: normal; font-size: 12px;">
- <td colspan="2">Remark:</td>
- <td colspan="9"></td>
- </tr>
- <tr style="text-align: left; font-weight: normal; font-size: 12px;">
- <td colspan="4">{$invoiceRemark}</td>
- <td colspan="7"></td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr>
- <td colspan="11"></td>
- </tr>
- <tr>
- <td colspan="11"></td>
- </tr>
- <tr>
- <td colspan="11"></td>
- </tr>
- <tr>
- <td colspan="11"></td>
- </tr>
- </table>
-
- <table style="table-layout: fixed;" class="table-noborder">
- <tr style="text-align: left; font-weight: normal; font-size: 12px;">
- <td colspan="4">Issued By:</td>
- <td colspan="4">Picked By:</td>
- <td colspan="3">Received By:</td>
- </tr>
- <tr>
- <td colspan="11"></td>
- </tr>
- </table>
- </div>
- </div>
- </body>
- </html>
- ORDER;
- require_once (\Yii::$app->vendorPath . '/tecnickcom/tcpdf/tcpdf.php');
- $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
- // 设置打印模式
- $pdf->SetCreator(PDF_CREATOR);
- $pdf->SetAuthor('DaZe');
- $pdf->SetTitle($orderSn);
- $pdf->SetSubject('TCPDF Tutorial');
- $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
- // 是否显示页眉
- $pdf->setPrintHeader(false);
- // 设置页眉字体
- $pdf->setHeaderFont(Array('dejavusans', '', '12'));
- // 页眉距离顶部的距离
- $pdf->SetHeaderMargin('5');
- // 是否显示页脚
- $pdf->setPrintFooter(false);
- // 设置默认等宽字体
- $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
- // 设置行高
- // $pdf->setCellHeightRatio(1);
- // 设置左、上、右的间距
- $pdf->SetMargins('5', '0', '5');
- // 设置是否自动分页 距离底部多少距离时分页
- $pdf->SetAutoPageBreak(TRUE, '15');
- // 设置图像比例因子
- $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
- if (@file_exists(\Yii::$app->vendorPath . 'tecnickcom/tcpdf/examples/lang/eng.php')) {
- require_once(\Yii::$app->vendorPath . '/tecnickcom/tcpdf/examples/lang/eng.php');
- $pdf->setLanguageArray($l);
- }
- $pdf->setFontSubsetting(true);
- $pdf->AddPage();
- // 设置字体
- $pdf->SetFont('stsongstdlight', '', 10, '', true);
- // $image_file = \Yii::$app->basePath . '/../ngds-logo.jpg';
- // $image = file_get_contents($image_file);
- // $pdf->Image('@' . $image, 15, 12, 20, 7, 'JPG');
- $pdf->writeHTML($context);
- $result = $pdf->Output($realFile, 'F');
- $this->_updateFirst($realFile, 1);
- }
- $this->complete();
- return true;
- }
- }
|