Commit f477dea9 authored by hangjun83's avatar hangjun83

药明康德

parent 28426dfe
<?php <?php
namespace App\Export; namespace App\ImportExport;
use App\Services\SysLogService; use App\Services\SysLogService;
use App\Support\Facades\SimpleLogs;
use Maatwebsite\Excel\Facades\Excel; use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Excel as BaseExcel; use Maatwebsite\Excel\Excel as BaseExcel;
...@@ -26,14 +27,23 @@ class BaseExport ...@@ -26,14 +27,23 @@ class BaseExport
public function storeExcel($excelContent, $filePath, $diskType = null){ public function storeExcel($excelContent, $filePath, $diskType = null){
if($diskType == null){ if($diskType == null){
$diskType = config('filesystem.default'); $diskType = config('filesystems.default');
} }
$result = Excel::store($excelContent,$filePath,$diskType, $this->expand); try{
$logContent = [ if(Excel::store($excelContent,$filePath,$diskType, $this->expand)){
'filePath' => $filePath, $logContent = [
'diskType' => $diskType, 'filePath' => $filePath,
'datetime' => time() 'diskType' => $diskType,
]; 'datetime' => time()
app(SysLogService::class)->addOperationLogs($logContent); ];
SimpleLogs::writeLog($logContent,__CLASS__.':storeExcel');
return true;
}
return false;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':storeExcel', 'error');
throw $exception;
}
} }
} }
<?php <?php
namespace App\Export\WuxiLab\Models; namespace App\ImportExport\WuxiLab\Models;
use Maatwebsite\Excel\Concerns\FromArray; use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize; use Maatwebsite\Excel\Concerns\ShouldAutoSize;
...@@ -32,7 +32,7 @@ class WuxiLabPackagesExportModel implements FromArray,WithHeadings, ShouldAutoSi ...@@ -32,7 +32,7 @@ class WuxiLabPackagesExportModel implements FromArray,WithHeadings, ShouldAutoSi
array_push($exportRows,['','','','','','','','','','','','','','','','','','','']); array_push($exportRows,['','','','','','','','','','','','','','','','','','','']);
foreach($rows as $key => $row){ foreach($rows as $key => $row){
array_push($exportRows,[ array_push($exportRows,[
$row['r_code'], '', $row['p_pack'].'/'.$row['p_pack_unit'], $row['p_stock'] == 0 ? '0' : $row['p_stock'], 'CN-SH', $row['p_price'], '0.5', $row['r_code'], '', $row['p_pack'].''.$row['p_pack_unit'], $row['p_stock'] == 0 ? '0' : $row['p_stock'], 'CN-SH', $row['p_price'], '0.5',
'RMB', 'CN', $row['p_price'] * 0.5 'RMB', 'CN', $row['p_price'] * 0.5
]); ]);
} }
......
<?php <?php
namespace App\Export\WuxiLab\Models; namespace App\ImportExport\WuxiLab\Models;
use Maatwebsite\Excel\Concerns\FromArray; use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize; use Maatwebsite\Excel\Concerns\ShouldAutoSize;
......
<?php <?php
namespace App\Export\WuxiLab\Models; namespace App\ImportExport\WuxiLab\Models;
use Maatwebsite\Excel\Concerns\FromArray; use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize; use Maatwebsite\Excel\Concerns\ShouldAutoSize;
......
<?php <?php
namespace App\Export\WuxiLab; namespace App\ImportExport\WuxiLab;
use App\Export\BaseExport; use App\ImportExport\BaseExport;
use App\Export\WuxiLab\Models\WuxiLabPackagesExportModel; use App\ImportExport\WuxiLab\Models\WuxiLabPackagesExportModel;
use App\Export\WuxiLab\Models\WuxiLabProductsExportModel; use App\ImportExport\WuxiLab\Models\WuxiLabProductsExportModel;
use App\Export\WuxiLab\Models\WuxiLabStocksExportModel; use App\ImportExport\WuxiLab\Models\WuxiLabStocksExportModel;
class WuxiLabExport extends BaseExport class WuxiLabExport extends BaseExport
{ {
...@@ -21,7 +21,7 @@ class WuxiLabExport extends BaseExport ...@@ -21,7 +21,7 @@ class WuxiLabExport extends BaseExport
public function getSavePath($fileName) public function getSavePath($fileName)
{ {
if($this->filePath == ''){ if($this->filePath == ''){
$this->filePath = config('filesystem.default').'/public/Excel/'; $this->filePath = config('filesystems.default.root').'public/Excel/';
} }
return $this->filePath.date('Ymd',time()).'/'.$fileName; return $this->filePath.date('Ymd',time()).'/'.$fileName;
} }
...@@ -36,32 +36,30 @@ class WuxiLabExport extends BaseExport ...@@ -36,32 +36,30 @@ class WuxiLabExport extends BaseExport
* @param $saveContent * @param $saveContent
* @param null $model * @param null $model
*/ */
public function saveExcel($saveContent,$model = null) public function saveExcel($saveContent,$model = 'product')
{ {
if($model == null){ if(!is_array($model) && $model == null){
$model = $this->defaultExportModel; throw new \Exception('excel 文档生成错误,无法找到对应生成类型!');
} }
if(!is_array($model) && $model != null){ $export = null;
$model = explode(',',$model); switch($model){
case 'product' :
$export = new WuxiLabProductsExportModel($saveContent['rawList']);
break;
case 'package' :
$export = new WuxiLabPackagesExportModel($saveContent['packageList']);
break;
case 'stock' :
$export = new WuxiLabStocksExportModel($saveContent['packageList']);
break;
} }
$savePath = $this->getSavePath(
foreach($model as $m){ $this->getFileName($model)
switch($m){ );
case 'product' : $result = $this->storeExcel($export,$savePath);
$export = new WuxiLabProductsExportModel($saveContent['rawList']); if($result){
break; return $savePath;
case 'package' :
$export = new WuxiLabPackagesExportModel($saveContent['packageList']);
break;
case 'stock' :
$export = new WuxiLabStocksExportModel($saveContent['packageList']);
break;
}
$savePath = $this->getSavePath(
$this->getFileName($m)
);
$this->storeExcel($export,$savePath);
} }
} }
} }
...@@ -47,6 +47,9 @@ class WuxiLabJob extends Job ...@@ -47,6 +47,9 @@ class WuxiLabJob extends Job
case 'batchUpdateProduct' : case 'batchUpdateProduct' :
$service->batchUpdateProducts(); $service->batchUpdateProducts();
break; break;
case 'test' :
$service->test($this->params);
break;
default: default:
} }
} }
......
...@@ -54,6 +54,19 @@ class RhawnRawRepositoryEloquent extends BaseRepository implements RhawnRawRepos ...@@ -54,6 +54,19 @@ class RhawnRawRepositoryEloquent extends BaseRepository implements RhawnRawRepos
return $rawList->toArray(); return $rawList->toArray();
} }
public function getRawProductsThroughtCode($rawCode)
{
$raw = RhawnRaw::query()
->join('chemicals', 'chemicals.c_id','raw.c_id');
if(!is_array($rawCode)){
$raw->where('r_code',$rawCode);
}else{
$raw->whereIn('r_code',!is_array($rawCode));
}
$rawList = $raw->get();
return $rawList->toArray();
}
public function getProductPackage($rawProductIds) public function getProductPackage($rawProductIds)
{ {
$packagesList = RhawnProducts::query() $packagesList = RhawnProducts::query()
......
...@@ -15,31 +15,6 @@ use Prettus\Validator\Contracts\ValidatorInterface; ...@@ -15,31 +15,6 @@ use Prettus\Validator\Contracts\ValidatorInterface;
*/ */
class ThirdApiPlatformRepositoryEloquent extends BaseRepository implements ThirdApiPlatformRepository class ThirdApiPlatformRepositoryEloquent extends BaseRepository implements ThirdApiPlatformRepository
{ {
protected $fieldSearchable = [
'platform_name', 'platform_title',
];
/**
* 定义validator的检索规则
* @var \string[][]
*/
public $rules = [
ValidatorInterface::RULE_CREATE => [
'platform_name' => 'required',
'platform_title' => 'required',
'platform_type' => 'required',
'platform_token' => 'required',
'platform_status' => 'required',
],
ValidatorInterface::RULE_UPDATE => [
'platform_name' => 'required',
'platform_title' => 'required',
'platform_type' => 'required',
'platform_token' => 'required',
'platform_status' => 'required',
]
];
/** /**
* Specify Model class name. * Specify Model class name.
* *
......
...@@ -14,6 +14,7 @@ namespace App\Services\ThirdPlatform\Api; ...@@ -14,6 +14,7 @@ namespace App\Services\ThirdPlatform\Api;
use App\ImportExport\WuxiLab\WuxiLabExport; use App\ImportExport\WuxiLab\WuxiLabExport;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\ThirdPlatform\PlatformAbstractService; use App\Services\ThirdPlatform\PlatformAbstractService;
use App\Support\Facades\SimpleLogs;
use App\Support\Traits\HttpClientHelpers; use App\Support\Traits\HttpClientHelpers;
...@@ -40,21 +41,21 @@ class WuxiApiService extends PlatformAbstractService ...@@ -40,21 +41,21 @@ class WuxiApiService extends PlatformAbstractService
$params = []; $params = [];
$params['chemicalProducts'] = $this->mergeApiMetaData($product); $params['chemicalProducts'] = $this->mergeApiMetaData($product);
$response = $this->getPostClient('https://api.uploadcatalog.com/api/v1/update',$params, [ $response = $this->getPostClient($this->platformInfo['platform_url'].'/api/v1/update',$params, [
$this->platformInfo['platform_params']['username'], $this->platformInfo['platform_params']['password'] $this->platformInfo['platform_params']['username'], $this->platformInfo['platform_params']['password']
]); ]);
return $this->apiResponse($response); return $this->apiResponse($response);
} }
}catch(\Exception $e){ }catch(\Exception $e){
return $this->requestError($e); $this->requestError($e);
} }
} }
public function backgroundLogin() public function backgroundLogin()
{ {
if($this->checkPlatformStatus()){ if($this->checkPlatformStatus()){
$response = $this->getPostClient('https://www.uploadcatalog.com/json_login',[ $response = $this->getPostClient($this->platformInfo['platform_params']['adminUrl'].'/json_login',[
'username' => $this->platformInfo['platform_params']['username'], 'username' => $this->platformInfo['platform_params']['username'],
'password' => $this->platformInfo['platform_params']['password'] 'password' => $this->platformInfo['platform_params']['password']
],null,[ ],null,[
...@@ -65,51 +66,154 @@ class WuxiApiService extends PlatformAbstractService ...@@ -65,51 +66,154 @@ class WuxiApiService extends PlatformAbstractService
} }
} }
public function pushBatchUploadProducts($token)
public function pushBatchUploadFile($type, $fileName, $token)
{ {
if($this->checkPlatformStatus()){ if($this->checkPlatformStatus()){
$params = [];
$params['companyId'] = '6789';
$params['type'] = 'PRODUCT_CHEMICAL';
$params['batchId'] = '7d686e0b-8a08-e9e9-7d1f-916c387dea08';
$filePath = app(WuxiLabExport::class)->getSavePath('wuxiLab_package_2022_08_08_063609');
$params['file'] = fopen($filePath.'.csv','r');
$cookie = 'org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN;Auth-Token='.$token.';'; switch($type){
case 'product' : $type = 'PRODUCT_CHEMICAL';break;
$response = $this->getPostClient('https://www.uploadcatalog.com/excel/chemical/upload',$params,null,[ case 'package' : $type = 'PACKAGE_CHEMICAL';break;
'cookie' => $cookie case 'stock' : $type = 'INVENTORY_CHEMICAL';break;
]); }
return json_decode($response,true)['token']; $params = [];
$params['companyId'] = $this->platformInfo['platform_params']['companyId'];
$params['type'] = $type;
$params['batchId'] = '65d30cab-92b7-8d4a-ae00-d5474c93d4f7';
$filePath = app(WuxiLabExport::class)->getSavePath($fileName);
$filePath = storage_path('app/'.$filePath);
$params['file']['name'] = $fileName.'.xlsx';
$params['file']['contents'] = \GuzzleHttp\Psr7\Utils::tryFopen($filePath.'.xlsx','r');
try{
$response = $this->getMultipartPostClient($this->platformInfo['platform_params']['adminUrl'].'/excel/chemical/upload',$params,null,[
'cookie' => $this->getCookie($token),
]);
if($this->apiResponse($response)){
unset($params['file']);
$urlParams = [];
foreach($params as $key => $param){
$urlParams[] = $key.'='.$param;
}
$confirmResponse = $this->clientRequest('post',
$this->platformInfo['platform_params']['adminUrl'].'/excel/finish?'.implode('&',$urlParams),
[
'headers' => [
'cookie' => $this->getCookie($token),
'content-type' => 'application/json;charset=UTF-8'
]
]);
$result = $this->apiResponse($confirmResponse);
if($result['success'] == true){
return true;
}
}
return false;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':pushBatchUploadProducts', 'error');
//file_put_contents('./error.txt',$exception->getMessage());
}
} }
} }
/**
* @更新包装规格
* @param $packages
* @param $token
* @return false|mixed|void
*/
public function pushBatchUpdatePackages($packages,$token) public function pushBatchUpdatePackages($packages,$token)
{ {
try{ try{
if($this->checkPlatformStatus()){ if($this->checkPlatformStatus()){
$params = []; $params = [];
$params['company_id'] = '6789'; $params['company_id'] = $this->platformInfo['platform_params']['companyId'];
$params['product_type'] = 'CHAMICAL'; $params['product_type'] = 'CHAMICAL';
$params = array_merge($params,$packages); $params = array_merge($params,$packages);
$cookie = 'org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN;Auth-Token='.$token.';'; $response = $this->getPostClient($this->platformInfo['platform_params']['adminUrl'].'/package/specification/save',$params,null, [
'cookie' => $this->getCookie($token)
$response = $this->getPostClient('https://www.uploadcatalog.com/package/specification/save',$params,null, [
'cookie' => $cookie
]); ]);
return $this->apiResponse($response); return $this->apiResponse($response);
} }
}catch(\Exception $e){ }catch(\Exception $e){
return $this->requestError($e); $this->requestError($e);
}
}
public function getPackageList($token)
{
try{
if($this->checkPlatformStatus()){
$params = [];
$params['companyId'] = $this->platformInfo['platform_params']['companyId'];
$params['productType'] = 'CHAMICAL';
$urlParams = [];
foreach($params as $key => $param){
$urlParams[] = $key.'='.$param;
}
$response = $this->clientRequest('get',
$this->platformInfo['platform_params']['adminUrl'].'/package/specification/count?'.implode('&',$urlParams),
[
'headers' => [
'cookie' => $this->getCookie($token),
'content-type' => 'application/json;charset=UTF-8'
]
]);
if($response && $response > 0){
$page = 1;
$count = ceil($response / 30);
$packageList = [];
while(true){
$params['page'] = $page;
$params['rows'] = 30;
$urlParams = [];
foreach($params as $key => $param){
$urlParams[] = $key.'='.$param;
}
$packageListResponse = $this->clientRequest('get',
$this->platformInfo['platform_params']['adminUrl'].'/package/specification/list?'.implode('&',$urlParams),
[
'headers' => [
'cookie' => $this->getCookie($token),
'content-type' => 'application/json;charset=UTF-8'
]
]);
$result = $this->apiResponse($packageListResponse);
if($result){
$packageList = array_merge($packageList,$result);
}
$page ++;
if($page > $count){
break;
}
sleep(2);
}
return $packageList;
}
return $this->apiResponse($response);
}
}catch(\Exception $e){
$this->requestError($e);
} }
} }
private function getCookie($token)
{
return 'org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN;Auth-Token='.$token.';';
}
/** /**
* 整理组装 api 数据 * 整理组装 api 数据
* @param $metaData * @param $metaData
...@@ -123,7 +227,6 @@ class WuxiApiService extends PlatformAbstractService ...@@ -123,7 +227,6 @@ class WuxiApiService extends PlatformAbstractService
$mergeData = []; $mergeData = [];
foreach($metaData['rawList'] as $datas){ foreach($metaData['rawList'] as $datas){
$tempData['supplier_product_id'] = $datas['r_code']; $tempData['supplier_product_id'] = $datas['r_code'];
$tempData['mdl'] = ''; $tempData['mdl'] = '';
$tempData['cas'] = $datas['c_cas']; $tempData['cas'] = $datas['c_cas'];
...@@ -148,8 +251,11 @@ class WuxiApiService extends PlatformAbstractService ...@@ -148,8 +251,11 @@ class WuxiApiService extends PlatformAbstractService
if(isset($metaData['packageList'][$datas['r_code']])){ if(isset($metaData['packageList'][$datas['r_code']])){
$package = $metaData['packageList'][$datas['r_code']]; $package = $metaData['packageList'][$datas['r_code']];
$pack['unit_description'] = $package['p_pack_unit']; $pack['unit_description'] = $package['p_pack_unit'];
$pack['package_status'] = $package['p_status'] == '1' ? 'ACTIVE' : 'INACTIVE'; $pack['package_status'] = $package['p_status'] == '1' && $package['p_show'] == '1' ? 'ACTIVE' : 'INACTIVE';
$tempData['status'] = $package['p_show'] == '1' ? 'ACTIVE' : 'INACTIVE';
$pack['inventorys'] = [ $pack['inventorys'] = [
'package_quantity' => $package['p_stock'], 'package_quantity' => $package['p_stock'],
'stock_status' => $package['p_stock'] > 0 ? 'INSTOCK' : 'OUTSTOK', 'stock_status' => $package['p_stock'] > 0 ? 'INSTOCK' : 'OUTSTOK',
...@@ -188,16 +294,14 @@ class WuxiApiService extends PlatformAbstractService ...@@ -188,16 +294,14 @@ class WuxiApiService extends PlatformAbstractService
{ {
$decodeResponse = json_decode($response,true); $decodeResponse = json_decode($response,true);
if($decodeResponse){ if($decodeResponse){
if(!empty($decodeResponse['successProduct'])){ return $decodeResponse;
return true;
}
} }
return false; return false;
} }
protected function requestError($response) protected function requestError($response)
{ {
return false; SimpleLogs::writeLog($response->getMessage(), 'WuxiApi error', 'error');
throw $response;
} }
} }
...@@ -362,7 +362,7 @@ class ZhenkhApiService extends PlatformAbstractService ...@@ -362,7 +362,7 @@ class ZhenkhApiService extends PlatformAbstractService
protected function requestError($response) protected function requestError($response)
{ {
SimpleLogs::writeLog($response->getMessage(), 'api error', 'error'); SimpleLogs::writeLog($response->getMessage(), 'Zhenkh api error', 'error');
throw $response; throw $response;
} }
......
...@@ -112,6 +112,6 @@ abstract class PlatformAbstractService ...@@ -112,6 +112,6 @@ abstract class PlatformAbstractService
public function removePlatformDataEntries($dataKey) public function removePlatformDataEntries($dataKey)
{ {
return $this->dataEntriesService->removeEntriesValues($dataKey); return $this->dataEntriesService->removeEntriesValues($this->getPlatformInfo('id'),$dataKey);
} }
} }
...@@ -18,7 +18,10 @@ use App\Repositories\Models\RhawnProducts; ...@@ -18,7 +18,10 @@ use App\Repositories\Models\RhawnProducts;
use App\Services\Kafka\KafkaService; use App\Services\Kafka\KafkaService;
use App\Services\ThirdPlatform\Api\WuxiApiService; use App\Services\ThirdPlatform\Api\WuxiApiService;
use App\Services\ThirdPlatform\PlatformAbstractService; use App\Services\ThirdPlatform\PlatformAbstractService;
use App\Support\Facades\SimpleKafka;
use App\Support\Facades\SimpleLogs;
use App\Support\Traits\Helpers; use App\Support\Traits\Helpers;
use Illuminate\Filesystem\Filesystem;
use longlang\phpkafka\Protocol\ApiVersions\ApiVersionsResponse; use longlang\phpkafka\Protocol\ApiVersions\ApiVersionsResponse;
class WuxiLabService class WuxiLabService
...@@ -27,6 +30,7 @@ class WuxiLabService ...@@ -27,6 +30,7 @@ class WuxiLabService
public function __construct() public function __construct()
{ {
$this->apiService = (new WuxiApiService(app(ThirdApiPlatformRepository::class))); $this->apiService = (new WuxiApiService(app(ThirdApiPlatformRepository::class)));
$this->rhawnChemicalsService = app(RhawnChemicalsService::class);
} }
/** /**
...@@ -36,12 +40,11 @@ class WuxiLabService ...@@ -36,12 +40,11 @@ class WuxiLabService
{ {
$status = $this->apiService->checkPlatformStatus(); $status = $this->apiService->checkPlatformStatus();
if($status){ if($status){
$rhawnChemicalsService = app(RhawnChemicalsService::class); $limit = $this->apiService->getPlatformInfo('platform_params')['batchNums'];
$limit = $this->platformInfo['platform_params']['batchNums'];
$page = 0; $page = 0;
while(true) { while(true) {
$rawList = $rhawnChemicalsService->getChemicalRawList($page * $limit, $limit); $rawList = $this->rhawnChemicalsService->getChemicalRawList($page * $limit, $limit);
if (!$rawList) { if (!$rawList) {
break; break;
} }
...@@ -49,7 +52,7 @@ class WuxiLabService ...@@ -49,7 +52,7 @@ class WuxiLabService
foreach ($rawList as $raw) { foreach ($rawList as $raw) {
$rawIdList[] = $raw['r_id']; $rawIdList[] = $raw['r_id'];
} }
$packages = $rhawnChemicalsService->getChemicalPackage($rawIdList); $packages = $this->rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = []; $newPackages = [];
if($packages){ if($packages){
foreach($packages as $pack){ foreach($packages as $pack){
...@@ -57,13 +60,14 @@ class WuxiLabService ...@@ -57,13 +60,14 @@ class WuxiLabService
} }
} }
if(!empty($rawList)){ if(!empty($rawList)){
app(KafkaService::class)->produerSend( SimpleKafka::produerSend(
[ [
'params' => ['rawList' => $rawList,'packageList' => $newPackages], 'params' => ['rawList' => $rawList,'packageList' => $newPackages],
'consumer' => 'App\Services\WuxiLabService', 'consumer' => __CLASS__,
'method' => 'batchUpdateApi' 'method' => 'batchUpdateToWuxiLab'
] ],
'wuxilab'
); );
} }
break; break;
...@@ -71,23 +75,67 @@ class WuxiLabService ...@@ -71,23 +75,67 @@ class WuxiLabService
} }
} }
public function test($rawCode)
{
try{
$rawsList = $this->rhawnChemicalsService->getChemicalRawThroughtCode($rawCode);
if($rawsList){
foreach ($rawsList as $raw) {
$rawIdList[] = $raw['r_id'];
}
$packages = $this->rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = [];
if($packages){
foreach($packages as $pack){
$newPackages[$pack['r_code']] = $pack;
}
}
/*$path = app(WuxiLabExport::class)->saveExcel(
['rawList' => $rawsList,'packageList' => $newPackages],
'package'
);
if($path){
list($file,$expend) = explode('.',$path);
$newPath = $file.'.'.strtolower($expend);
$cmd = 'mv '.storage_path('app/'.$path).' '.storage_path('app/'.$newPath);
trim(shell_exec("$cmd 2>&1"));
$filePathList = explode('/',$file);
$fileName = $filePathList[count($filePathList) - 1];
$result = $this->apiService->pushBatchUploadFile('package',$fileName, $this->apiService->backgroundLogin());
if($result){
$cmd = 'rm -rf '.storage_path('app/'.$newPath);
trim(shell_exec("$cmd 2>&1"));
SimpleLogs::writeLog('文件名为:'.$fileName.'路径:'.$newPath.'药明康德后台上传完成', __CLASS__.':processNotExistProductsUpdate');
}
}*/
$result = $this->apiService->pushBatchUpdateProduct(['rawList' => $rawsList,'packageList' => $newPackages]);
var_dump($result);
}
}catch(\Throwable $exception){
var_dump($exception->getMessage());
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':processNotExistProductsUpdate', 'error');
}
}
/**
* @批量后台请求更新规格
* @param null $params
*/
public function batchUpdatePackagesInfo($params = null) public function batchUpdatePackagesInfo($params = null)
{ {
$token = $this->apiService->backgroundLogin(); $token = $this->getToken();
$wuxiLabPackage = ['bottle','box','bp','case','ea','g','gal','hole','kg','kit','l','m','m2','mg','ml','mm','mmol','mu', $wuxiLabPackage = ['bottle','box','bp','case','ea','g','gal','hole','kg','kit','l','m','m2','mg','ml','mm','mmol','mu',
'ng','nmole','od','package','pair','piece','pmole','RL','sets','test', 'unit','vial','xa','µci','µg','µl','µmol']; 'ng','nmole','od','package','pair','piece','pmole','RL','sets','test', 'unit','vial','xa','µci','µg','µl','µmol'];
/*$rhawnChemicalsService = app(RhawnChemicalsService::class); //$path = config('filesystems.disks.local.root').'/upload/'.$params;
$packagesUnit = $rhawnChemicalsService->getProductPackagesThroughGroupByPackUnit();*/ //$generator = Helpers::yieldLoadCsv($path);
$path = config('filesystems.disks.local.root').'/upload/'.$params;
$generator = Helpers::yieldLoadCsv($path);
// yield 循环逐行读取csv内容 // yield 循环逐行读取csv内容
while ($generator->valid()) { /*while ($generator->valid()) {
$content = $generator->current(); $content = $generator->current();
var_dump($content);
if(in_array($content[1],$wuxiLabPackage)){ if(in_array($content[1],$wuxiLabPackage)){
$this->apiService->pushBatchUpdatePackages([ $this->apiService->pushBatchUpdatePackages([
'unit_quantity' => $content[0], 'unit_type' => $content[1], 'unit_description' => $content[0].$content[1] 'unit_quantity' => $content[0], 'unit_type' => $content[1], 'unit_description' => $content[0].$content[1]
...@@ -95,53 +143,194 @@ class WuxiLabService ...@@ -95,53 +143,194 @@ class WuxiLabService
} }
usleep(30000); usleep(30000);
$generator->next(); $generator->next();
} }*/
$packageList = $this->apiService->getPackageList($token);
/*foreach($packagesUnit as $unit){ $rhawnChemicalsService = app(RhawnChemicalsService::class);
if(in_array($unit['p_pack_unit'],$wuxiLabPackage)){ $packagesUnit = $rhawnChemicalsService->getProductPackagesThroughGroupByPackUnit();
$service->pushBatchUpdatePackages([
'unit_quantity' => $unit['p_pack'], 'unit_type' => $unit['p_pack_unit'], 'unit_description' => $unit['p_pack'].$unit['p_pack_unit'] foreach($packagesUnit as $package){
],$token); if(!empty($packageList)){
$exist = 0;
foreach($packageList as $p){
$name = $package['p_pack'].$package['p_pack_unit'];
if($name == $p['unitDescription']){
$exist = 1;
}
}
if(!$exist){
if(!in_array($package['p_pack_unit'],$wuxiLabPackage)){
continue;
}
$this->apiService->pushBatchUpdatePackages([
'unit_quantity' => $package['p_pack'], 'unit_type' => $package['p_pack_unit'], 'unit_description' => $package['p_pack'].$package['p_pack_unit']
],$token);
}
} }
}*/ }
} }
public function batchUploadProducts() /**
* @处理不存在商品的更新
* @param $params
* @return false|void
*/
public function processProductsUpdateThroughtExcel($params)
{ {
//$token = $service->backgroundLogin(); if(!isset($params['products']) || empty($params['products'])){
return false;
}
$token = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI3OTAwODcwNTlAcXEuY29tIiwiaXNzIjoiTGFiTmV0d29yayIsImlhdCI6MTY2MDUyNTg0NiwiZXhwIjoxNjYwNTQ3NDQ2LCJyb2xlcyI6IlJPTEVfU1VQUExJRVIiLCJhcHBsaWNhdGlvbiI6ImZ1bGxtb29uIiwidG9rZW4iOiIwNmQ1ZWIyNy0yYjMxLTQ3NjUtYTIzNS1lOTJhMzJjMjFhMjAiLCJjb21wYW55IjoiWUVIWCIsInByZWZlcnJlZExhbmd1YWdlIjoiIiwiamRlSWQiOiI5MDI2MDkyIiwiY29tcGFueU5hbWUiOiLkuIrmtbfmmJPmganljJblrabmioDmnK_mnInpmZDlhazlj7gifQ.oVk2WQeR6NlTvruRrh4I_2YenvKTejyeOd5-tbgXe9g'; try{
$result = $this->apiService->pushBatchUploadProducts($token); $rawsList = $this->rhawnChemicalsService->getChemicalRawThroughtCode($params['products']);
if($rawsList){
foreach ($rawsList as $raw) {
$rawIdList[] = $raw['r_id'];
}
$packages = $this->rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = [];
if($packages){
foreach($packages as $pack){
$newPackages[$pack['r_code']] = $pack;
}
}
$path = app(WuxiLabExport::class)->saveExcel(
['rawList' => $rawsList,'packageList' => $newPackages]
);
if($path){
list($file,$expend) = explode('.',$path);
$newPath = $file.'.'.strtolower($expend);
$cmd = 'mv '.storage_path('app/'.$path).' '.storage_path('app/'.$newPath);
trim(shell_exec("$cmd 2>&1"));
$filePathList = explode('/',$file);
$fileName = $filePathList[count($filePathList) - 1];
$result = $this->apiService->pushBatchUploadFile($params['type'],$fileName, $this->getToken());
if($result){
SimpleLogs::writeLog('文件名为:'.$fileName.'路径:'.$newPath.'药明康德后台上传完成', __CLASS__.':processNotExistProductsUpdate');
}
}
}
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':processNotExistProductsUpdate', 'error');
}
} }
public function batchUpdateApi($updateData) /**
* @批量更新商品
* @param $updateData
*/
public function batchUpdateToWuxiLab($updateData)
{ {
$result = $this->apiService->pushBatchUpdateProduct($updateData); if(!isset($updateData['rawList']) || empty($updateData['rawList'])){
if($result){ return false;
if($result['status'] === false){ }
app(KafkaService::class)->produerSend( if(!isset($updateData['packageList']) || empty($updateData['packageList'])){
[ return false;
'' =>'', }
'params' => $updateData try{
] $result = $this->apiService->pushBatchUpdateProduct($updateData);
); if($result){
if(isset($result['errorProduct']) && !empty($result['errorProduct'])){
$storeEntries = $this->apiService->getPlatformDataEntries('wuxiLab_not_exist_products','data_values');
/*if(!is_null($storeEntries) && count($storeEntries['products']) >= $this->apiService->getPlatformInfo('platform_params')['excelCreateLimit']){
SimpleKafka::produerSend(
[
'params' => ['products' => $storeEntries['products'],'type' => 'product'],
'consumer' => __CLASS__,
'method' => 'processProductsUpdateThroughtExcel'
]
);
$this->apiService->removePlatformDataEntries('wuxiLab_not_exist_products');
$storeEntries = null;
}*/
foreach($result['errorProduct'] as $errorProduct){
if($errorProduct['reason'] == 'PRODUCT_NOT_EXIST'){
if(!is_null($storeEntries) && !empty($storeEntries['products'])){
if(!in_array($errorProduct['data'],$storeEntries['products'])){
array_push($storeEntries['products'],$errorProduct['data']);
}
}else{
$storeEntries['products'][] = $errorProduct['data'];
}
}
}
$this->apiService->storePlatformDataEntries('wuxiLab_not_exist_products',['products' => $storeEntries['products']]);
}
//更新成功,批量更新包装规格
$storeEntries = $this->apiService->getPlatformDataEntries('wuxiLab_do_not_update_products','data_values');
if(!is_null($storeEntries) && count($storeEntries['products']) >= $this->apiService->getPlatformInfo('platform_params')['excelCreateLimit']){
SimpleKafka::produerSend(
[
'params' => ['products' => $storeEntries['products'],'type' => 'package'],
'consumer' => __CLASS__,
'method' => 'processProductsUpdateThroughtExcel'
]
);
$this->apiService->removePlatformDataEntries('wuxiLab_do_not_update_products');
}
foreach($result['successProduct'] as $successProduct){
if(!is_null($storeEntries) && !empty($storeEntries['products'])){
if(!in_array($successProduct,$storeEntries['products'])){
array_push($storeEntries['products'],$successProduct);
}
}else{
$storeEntries['products'][] = $successProduct;
}
}
} }
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':batchUpdateToWuxiLab', 'error');
var_dump($exception->getMessage());
} }
unset($result['status']); }
/**
* @ 获取api token
* @return false|mixed
*/
public function getToken(){
try{
$token = $this->apiService->getPlatformDataEntries('wuxilab_backlogin_token','data_values');
if(empty($token)){
$apiToken = $this->apiService->backgroundLogin();
if($apiToken){
$backloginToken = [];
$backloginToken['currentTime'] = time();
$backloginToken['token'] = $apiToken;
$this->apiService->storePlatformDataEntries('wuxilab_backlogin_token',$backloginToken);
return $apiToken;
}
}else{
//超过有效期,重新请求获取
if(intval(gmdate('i',time() - intval($token['currentTime']))) > 30){
$apiToken = $this->apiService->backgroundLogin();
if($apiToken){
$apiToken['currentTime'] = time();
$this->apiService->storePlatformDataEntries('zkh_api_token',$apiToken);
return $apiToken['token'];
}
}
return $token['token'];
}
}catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':token error', 'error');
return false;
}
} }
/** /**
* 初始化生成产品excel文档 * @初始化生成产品excel文档
* @param $exportLimit
*/ */
public function initCreateProductsToExcel($exportLimit) public function initCreateProductsToExcel($exportLimit)
{ {
$rhawnChemicalsService = app(RhawnChemicalsService::class);
$limit = $exportLimit; $limit = $exportLimit;
$page = 0; $page = 0;
while(true) { while(true) {
$rawList = $rhawnChemicalsService->getChemicalRawList($page * $limit, $limit); $rawList = $this->rhawnChemicalsService->getChemicalRawList($page * $limit, $limit);
if (!$rawList) { if (!$rawList) {
break; break;
} }
...@@ -149,7 +338,7 @@ class WuxiLabService ...@@ -149,7 +338,7 @@ class WuxiLabService
foreach ($rawList as $raw) { foreach ($rawList as $raw) {
$rawIdList[] = $raw['r_id']; $rawIdList[] = $raw['r_id'];
} }
$packages = $rhawnChemicalsService->getChemicalPackage($rawIdList); $packages = $this->rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = []; $newPackages = [];
if($packages){ if($packages){
foreach($packages as $pack){ foreach($packages as $pack){
......
...@@ -12,7 +12,7 @@ trait HttpClientHelpers ...@@ -12,7 +12,7 @@ trait HttpClientHelpers
{ {
$options = []; $options = [];
$options['headers']['User-Agent'] = $this->randomUserAgent(); $options['headers']['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER';
$options['debug'] = env('API_DEBUG'); $options['debug'] = env('API_DEBUG');
return $options; return $options;
...@@ -44,6 +44,39 @@ trait HttpClientHelpers ...@@ -44,6 +44,39 @@ trait HttpClientHelpers
return $this->clientRequest('post', $uri, $options); return $this->clientRequest('post', $uri, $options);
} }
public function getMultipartPostClient($uri, $paramsBody = [], $auth = null, $header = null)
{
$options = [
'headers' => []
];
$paramsOptions = [];
foreach($paramsBody as $key => $params){
if($key != 'file'){
array_push($paramsOptions,[
'name' => $key,
'contents' => $params
]);
}else{
array_push($paramsOptions,[
'name' => 'file',
'filename' => $params['name'],
'contents' => $params['contents']
]);
}
}
$options['multipart'] = $paramsOptions;
if($auth && is_array($auth)){
$options['auth'] = $auth;
}
if(!is_null($header)){
$options['headers'] = array_merge($options['headers'],$header);
}
return $this->clientRequest('post', $uri, $options);
}
protected function clientRequest($requestType, $uri,$options) protected function clientRequest($requestType, $uri,$options)
{ {
$requestOptions = $this->getDefaultOptions(); $requestOptions = $this->getDefaultOptions();
......
...@@ -3,14 +3,13 @@ ...@@ -3,14 +3,13 @@
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
class ThridApiPlatformSeeder extends Seeder class ThridApiPlatformSeeder extends Seeder
{ {
use \App\Support\Traits\Helpers; use \App\Support\Traits\Helpers;
protected $thirdapiplatform = [ protected $thirdapiplatform = [
/*[ [
'platform_name' => 'integle', 'platform_name' => 'integle',
'platform_title' => 'integle', 'platform_title' => 'integle',
'platform_url' => 'http://suppliers.integle.com', 'platform_url' => 'http://suppliers.integle.com',
...@@ -31,8 +30,8 @@ class ThridApiPlatformSeeder extends Seeder ...@@ -31,8 +30,8 @@ class ThridApiPlatformSeeder extends Seeder
'platform_type' => 'third', 'platform_type' => 'third',
'platform_status' => '1', 'platform_status' => '1',
'platform_token' => '', 'platform_token' => '',
],*/ ],
/*[ [
'platform_name' => 'bide', 'platform_name' => 'bide',
'platform_title' => 'bide', 'platform_title' => 'bide',
'platform_url' => 'http://220.248.71.110:9000', 'platform_url' => 'http://220.248.71.110:9000',
...@@ -42,8 +41,8 @@ class ThridApiPlatformSeeder extends Seeder ...@@ -42,8 +41,8 @@ class ThridApiPlatformSeeder extends Seeder
'platform_type' => 'third', 'platform_type' => 'third',
'platform_status' => '1', 'platform_status' => '1',
'platform_token' => '', 'platform_token' => '',
],*/ ],
/*[ [
'platform_name' => 'bjs', 'platform_name' => 'bjs',
'platform_title' => 'bjs', 'platform_title' => 'bjs',
'platform_url' => 'http://220.248.71.110:9000', 'platform_url' => 'http://220.248.71.110:9000',
...@@ -53,7 +52,7 @@ class ThridApiPlatformSeeder extends Seeder ...@@ -53,7 +52,7 @@ class ThridApiPlatformSeeder extends Seeder
'platform_type' => 'third', 'platform_type' => 'third',
'platform_status' => '1', 'platform_status' => '1',
'platform_token' => '', 'platform_token' => '',
],*/ ],
[ [
'platform_name' => 'zkh', 'platform_name' => 'zkh',
'platform_title' => '震坤行', 'platform_title' => '震坤行',
...@@ -89,7 +88,10 @@ class ThridApiPlatformSeeder extends Seeder ...@@ -89,7 +88,10 @@ class ThridApiPlatformSeeder extends Seeder
'username' => '790087059@qq.com', 'username' => '790087059@qq.com',
'password' => 'YXH1992xb', 'password' => 'YXH1992xb',
'auth' => 'dGVzdDEyMzpwYXNzNDU2', 'auth' => 'dGVzdDEyMzpwYXNzNDU2',
'batchNums' => '500' 'batchNums' => '500',
'companyId' => '6789',
'adminUrl' => 'https://www.uploadcatalog.com',
'excelCreateLimit' => 100
]); ]);
break; break;
case "bide" : case "bide" :
...@@ -121,7 +123,7 @@ class ThridApiPlatformSeeder extends Seeder ...@@ -121,7 +123,7 @@ class ThridApiPlatformSeeder extends Seeder
$platform['created_at'] = date('Y-m-d H:i:s',time()); $platform['created_at'] = date('Y-m-d H:i:s',time());
$platform['updated_at'] = date('Y-m-d H:i:s',time()); $platform['updated_at'] = date('Y-m-d H:i:s',time());
$thirdApiPlatformRepo->updateOrCreate($platform); $thirdApiPlatformRepo->updateOrCreate(['platform_name' => $platform['platform_name']],$platform);
} }
DB::commit(); DB::commit();
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment