Commit ecf8c45f authored by hj's avatar hj

更新提交

parent 222b8520
...@@ -60,50 +60,10 @@ class WuxiLabNewJobCommand extends Command ...@@ -60,50 +60,10 @@ class WuxiLabNewJobCommand extends Command
$service = app(WuxiLabNewService::class); $service = app(WuxiLabNewService::class);
switch($action_type){ switch($action_type){
case 'initProductToExcel' : case 'batchUpdateProducts': $service->batchUpdateProducts($params);break;
if(!isset($params) || $params == 0){ case 'batchUpdateProductPrice': $service->batchUpdateProductPrice($params);break;
$params['limit'] = 1000; case 'batchUpdateProductStock': $service->batchUpdateProductStock($params);break;
}
$service->initCreateProductsToExcel($params['limit']);
break;
case 'batchUpdatePackages' :
if(!isset($params) || $params == 0){
$params['limit'] = 1000;
}
$service->batchUpdatePackagesInfo($params);
break;
case 'batchUploadProducts' :
$service->batchUploadProducts();
break;
case 'batchUpdateToWuxiLab' :
$service->batchUpdateToWuxiLab();
break;
case 'batchUpdateProduct' :
$service->batchUpdateProducts();
break;
case 'test' :
$service->test($params);
break;
case 'test1' :
$service->test1();
break;
case 'batchUploadNewProducts' :
$service->batchUploadNewProducts();
break;
case 'batchUpdateProductPackages' :
$service->batchUploadPackages();
break;
case 'batchUpdateProductsShelves' :
$service->batchUpdateProductsShelves();
break;
case 'initToken' :
$service->initToken();
break;
default:
} }
/*$productUpdateJob = (new WuxiLabJob($action_type,$params))->delay(100)->onQueue('slow');
app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($productUpdateJob);*/
} }
} }
......
...@@ -67,6 +67,26 @@ class RhawnProductService ...@@ -67,6 +67,26 @@ class RhawnProductService
} }
} }
public function getProductsListThroughPids($pIds)
{
try{
$dbConnect = DB::connection('rhawn_mysql');
$product = $dbConnect->table('products')
->whereIn('p_id',(array)$pIds)
->get()->toArray();
if(count($product) > 0){
return $product;
}
return null;
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(),__CLASS__.':getRawProductsThroughPid ','error');
throw $exception;
}
}
/** /**
* 通过产品code查找 * 通过产品code查找
* @param $pCode * @param $pCode
......
<?php <?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Services\ThirdPlatform\Api; namespace App\Services\ThirdPlatform\Api;
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\Facades\SimpleLogs;
...@@ -29,27 +19,23 @@ class WuxiApiNewService extends PlatformAbstractService ...@@ -29,27 +19,23 @@ class WuxiApiNewService extends PlatformAbstractService
$this->getPlatformInfo(); $this->getPlatformInfo();
} }
public function getToken()
{
return $this->postApi('/token/fetch', [
'username' => '790087059@qq.com',
'password' => 'YXH19920517!!'
]);
}
/** /**
* 批量更新商品信息 * 批量更新商品信息
* @param $product * @param $product
* @return bool * @return bool
*/ */
public function pushBatchUpdateProduct($product) public function pushBatchUpdateProduct($product, $token)
{ {
try{ $params = $this->mergeApiMetaData($product);
if($this->checkPlatformStatus()){ return $this->postApi('/api/v2/updateChamical', $params, $token);
$params = $this->mergeApiMetaData($product);
$response = $this->getPostClient($this->platformInfo['platform_url'].'/api/v2/updateChamical',$params, null,
[
'authorization' => $this->getAuthHeader()
]
);
return $this->apiResponse($response);
}
}catch(\Exception $e){
$this->requestError($e);
}
} }
/** /**
...@@ -60,87 +46,17 @@ class WuxiApiNewService extends PlatformAbstractService ...@@ -60,87 +46,17 @@ class WuxiApiNewService extends PlatformAbstractService
*/ */
public function pushBatchUpdatePackages($packages,$token) public function pushBatchUpdatePackages($packages,$token)
{ {
try{ return $this->postApi('/api/v2/syncProductPackageStatus', $packages, $token);
if($this->checkPlatformStatus()){
$params = [];
$params['company_id'] = $this->platformInfo['platform_params']['companyId'];
$params['product_type'] = 'CHAMICAL';
$params = array_merge($params,$packages);
$response = $this->getPostClient($this->platformInfo['platform_params']['adminUrl'].'/package/specification/save',$params,null, [
//'cookie' => $this->getCookie($token)
]);
return $this->apiResponse($response);
}
}catch(\Exception $e){
$this->requestError($e);
}
} }
public function getPackageList($token) public function pushBatchUpdatePrice($prices,$token)
{ {
try{ return $this->postApi('/api/v2/syncPackagePrice', $prices, $token);
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); public function pushBatchUpdateStock($stock,$token)
} {
}catch(\Exception $e){ return $this->postApi('/api/v2/syncRealTimeInventory', $stock, $token);
$this->requestError($e);
}
} }
/** /**
...@@ -163,7 +79,8 @@ class WuxiApiNewService extends PlatformAbstractService ...@@ -163,7 +79,8 @@ class WuxiApiNewService extends PlatformAbstractService
$tempData['chinese_name'] = $datas['r_cn_name']; $tempData['chinese_name'] = $datas['r_cn_name'];
$tempData['english_name'] = $datas['r_en_name']; $tempData['english_name'] = $datas['r_en_name'];
$tempData['chemicalformula'] = $datas['c_fzs'] ?? ''; $tempData['chemicalformula'] = $datas['c_fzs'] ?? '';
$tempData['purity'] = $datas['r_level']; $tempData['purity'] = '00AR';//$datas['r_level'];
/*$tempData['usually_ships_days_min'] = ''; /*$tempData['usually_ships_days_min'] = '';
$tempData['usually_ships_within_days'] = ''; $tempData['usually_ships_within_days'] = '';
$tempData['backorder_lead_time'] = '';*/ $tempData['backorder_lead_time'] = '';*/
...@@ -182,6 +99,9 @@ class WuxiApiNewService extends PlatformAbstractService ...@@ -182,6 +99,9 @@ class WuxiApiNewService extends PlatformAbstractService
case 2: $tempData['transportation_condition'] = 1;break; case 2: $tempData['transportation_condition'] = 1;break;
} }
$tempData['smiles'] = $datas['c_smiles'];
$tempData['sub_category'] = 'INHIBITOR';
/*产品种类 /*产品种类
1: Templates/Scaffolds, 1: Templates/Scaffolds,
2: Amino Acids & 2: Amino Acids &
...@@ -203,49 +123,50 @@ Compounds, ...@@ -203,49 +123,50 @@ Compounds,
//$tempData['status'] = $datas['r_status'] == '1' ? 'ACTIVE' : 'INACTIVE'; //$tempData['status'] = $datas['r_status'] == '1' ? 'ACTIVE' : 'INACTIVE';
$tempData['inventorys'][] = [ /*$tempData['inventorys'][] = [
'type' => $datas['r_unit'], 'type' => $datas['r_unit'],
'quantity' => floatval($datas['r_stock']), 'quantity' => floatval($datas['r_stock']),
'country' => 'CN', 'country' => 'CN',
'stock_status' => $datas['r_stock'] > 0 ? 'INSTOCK' : 'OUTSTOCK', 'stock_status' => $datas['r_stock'] > 0 ? 'INSTOCK' : 'OUTSTOCK',
]; ];*/
$tempData['packages'] = []; $tempData['packages'] = [];
$currentPackageList = $metaData['packageList'];
if(isset($metaData['packageList'][$datas['r_code']])){ if(!empty($currentPackageList)){
$package = $metaData['packageList'][$datas['r_code']]; foreach($currentPackageList as $package){
$pack = [];
$pack['unit_description'] = $package['p_pack_unit']; if($package['r_code'] == $datas['r_code']){
//$pack['package_status'] = $package['p_status'] == '1' && $package['p_show'] == '1' && $package['p_if_big'] == 0 ? 'ACTIVE' : 'INACTIVE'; $pack['unit_description'] = $package['p_pack'].''.$package['p_pack_unit'];
//$tempData['status'] = $package['p_status'] == '1' && $package['p_show'] == '1' && $package['p_if_big'] == 0 ? 'ACTIVE' : 'INACTIVE'; //$pack['package_status'] = $package['p_status'] == '1' && $package['p_show'] == '1' && $package['p_if_big'] == 0 ? 'ACTIVE' : 'INACTIVE';
//$tempData['status'] = $package['p_status'] == '1' && $package['p_show'] == '1' && $package['p_if_big'] == 0 ? 'ACTIVE' : 'INACTIVE';
$pack['inventorys'] = [
'package_quantity' => $package['p_stock'], $pack['inventorys'][] = [
//'stock_status' => $package['p_stock'] > 0 ? 'INSTOCK' : 'OUTSTOK', 'package_quantity' => '1',//$package['p_stock'],
'country' => 'CN' //'stock_status' => $package['p_stock'] > 0 ? 'INSTOCK' : 'OUTSTOK',
]; 'country' => 'CN-SH'
];
$pack['prices'] = [
'price' => $package['p_price'], $pack['prices'][] = [
'currency' => 'RMB', 'price' => bcmul($package['p_price'], 0.5, 2),
//'status' => 'ACTIVE' 'currency' => 'RMB',
]; //'status' => 'ACTIVE'
];
/*$pack['costs'] = [
'In_cost' => $package['p_avg_cost'], /*$pack['costs'] = [
'In_cost_currency' => 'RMB', 'In_cost' => $package['p_avg_cost'],
'status' => $package['p_stock'] > 0 ? 'ACTIVE' : 'INACTVIE', 'In_cost_currency' => 'RMB',
];*/ 'status' => $package['p_stock'] > 0 ? 'ACTIVE' : 'INACTVIE',
];*/
$pack['wuxiPackagePricings'] = [
'discount'=> 0.00, $pack['wuxiPackagePricings'][] = [
'currency' => 'RMB', 'discount'=> 0.5,
//'status' => 'INACTIVE' 'currency' => 'RMB',
]; //'status' => 'INACTIVE'
];
$tempData['packages'][] = $pack; $tempData['packages'][] = $pack;
}
}
} }
$mergeData[] = $tempData; $mergeData[] = $tempData;
unset($tempData); unset($tempData);
} }
...@@ -253,26 +174,18 @@ Compounds, ...@@ -253,26 +174,18 @@ Compounds,
return $mergeData; return $mergeData;
} }
public function getAuthHeader() protected function postApi($apiUri, $postParams, $token = null)
{ {
$auth = $this->getPlatformDataEntries('wuxi_api_auth', 'data_values'); try {
if(!$auth){ if ($this->checkPlatformStatus()) {
$response = $this->getPostClient($this->platformInfo['platform_url'].'/token/fetch', [ $response = $this->getPostClient($this->platformInfo['platform_url'] . $apiUri, $postParams, null,
'username' => '790087059@qq.com', !is_null($token) ? [ 'Authorization' => 'Bearer ' . $token] : null
'password' => 'YXH1992xb!!' );
] return $this->apiResponse($response);
);
$result = $this->apiResponse($response);
if($result){
if($result['code'] == '200' && $result['success'] == 'true'){
$this->dataEntriesService->storeEntries(6, 'wuxi_api_auth',
['authorization' => $result['data']]
);
}
} }
return $result['data']; }catch(\Exception $e){
$this->requestError($e);
} }
return $auth['authorization'];
} }
protected function apiResponse($response) protected function apiResponse($response)
......
...@@ -31,7 +31,6 @@ abstract class PlatformAbstractService ...@@ -31,7 +31,6 @@ abstract class PlatformAbstractService
} }
protected function setPlatformName($platformName){ protected function setPlatformName($platformName){
$this->platformName = '';
$this->platformName = $platformName; $this->platformName = $platformName;
} }
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
namespace App\Services\ThirdPlatform; namespace App\Services\ThirdPlatform;
use App\ImportExport\WuxiLab\WuxiLabExport;
use App\Repositories\Contracts\ThirdApiPlatformRepository; use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Rhawn\Services\RhawnProductService; use App\Rhawn\Services\RhawnProductService;
use App\Services\ThirdPlatform\Api\WuxiApiNewService; use App\Services\ThirdPlatform\Api\WuxiApiNewService;
use App\Support\Facades\SimpleLogs; use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class WuxiLabNewService class WuxiLabNewService
{ {
...@@ -19,14 +19,13 @@ class WuxiLabNewService ...@@ -19,14 +19,13 @@ class WuxiLabNewService
public function initToken() public function initToken()
{ {
$this->getToken(); return $this->getToken();
//$this->apiService->removePlatformDataEntries('wuxilab_backlogin_token');
} }
/** /**
* 批量更新商品 * 批量更新商品
*/ */
public function batchUpdateProducts($params = null) public function batchUpdateProducts($type = 'all')
{ {
$status = $this->apiService->checkPlatformStatus(); $status = $this->apiService->checkPlatformStatus();
if($status){ if($status){
...@@ -54,291 +53,138 @@ class WuxiLabNewService ...@@ -54,291 +53,138 @@ class WuxiLabNewService
//$newPackages[$pack['r_code']] = $pack; //$newPackages[$pack['r_code']] = $pack;
} }
} }
if(!empty($rawList)){
$this->apiService->pushQueue([ $queueParams = [];
switch($type){
case 'all': $queueParams = [
'params' => ['rawList' => $rawList,'packageList' => $newPackages], 'params' => ['rawList' => $rawList,'packageList' => $newPackages],
'consumer' => __CLASS__, 'consumer' => __CLASS__,
'method' => 'batchUpdateTo' 'method' => 'queueBatchUpdateProductToApi'
];break;
case 'package': $queueParams = [
'params' => ['packageList' => $newPackages],
'consumer' => __CLASS__,
'method' => 'queueBatchUpdatePackagesToApi'
];break;
default:
$queueParams = [
'params' => ['rawList' => $rawList,'packageList' => $newPackages],
'consumer' => __CLASS__,
'method' => 'queueBatchUpdateProductToApi'
];
}
],'wuxilab_api'); if(!empty($rawList)){
$this->apiService->pushQueue($queueParams,'wuxilab_api');
} }
break;
$page ++; $page ++;
} }
} }
} }
/** /**
* 商品批量下架 * 批量更新产品价格
* @param null $params * @return void
* @throws \Exception * @throws \Exception
*/ */
public function batchUpdateProductsShelves($params = null) public function batchUpdateProductPrice()
{ {
$status = $this->apiService->checkPlatformStatus(); $status = $this->apiService->checkPlatformStatus();
if($status){ if($status){
$limit = $this->apiService->getPlatformInfo('platform_params')['batchNums']; $dbConnect = DB::connection('rhawn_mysql');
$page = 0;
ini_set('memory_limit','3072M'); $startime = date('Y-m-d', strtotime('-1 day')).' 00:00:00';
$rawCodeList = []; $endtime = date('Y-m-d', time()).' 00:00:00';
while(true) {
$rawList = $this->rhawnChemicalsService->getRawsList($page * $limit, $limit);
if (!$rawList) {
break;
}
foreach ($rawList as $raw) {
if(!in_array($raw['r_code'],$rawCodeList)){
array_push($rawCodeList,$raw['r_code']);
}
}
$page ++;
}
$path = app(WuxiLabExport::class)->saveExcel(
['rawCode' => $rawCodeList], 'product_shelves'
);
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->apiService->backgroundLogin());
if($result){
$cmd = 'rm -rf '.storage_path('app/'.$newPath);
trim(shell_exec("$cmd 2>&1"));
SimpleLogs::writeLog('文件名为:'.$fileName.'路径:'.$newPath.'药明康德后台上传完成', __CLASS__.':processNotExistProductsUpdate');
}*/
}
}
}
/** $product = $dbConnect->table('prochange')
* 批量更新新的商品 ->whereRaw("updatetime >=".strtotime($startime)." and updatetime <=".strtotime($endtime))
*/ ->where('type', '2')
public function batchUploadNewProducts() ->get()->toArray();
{ if(count($product) > 0){
$storeEntries = $this->apiService->getPlatformDataEntries('wuxiLab_not_exist_products','data_values'); $productIds = array_unique(array_column($product, 'p_id'));
if(isset($storeEntries['products']) && !empty($storeEntries['products'])){ $productList = $this->rhawnChemicalsService->getProductsListThroughPids($productIds);
$countNum = 0;
$products = []; $updateProductPrice = [];
foreach($storeEntries['products'] as $product){ foreach($productList as $product){
if(!in_array($product,$products) || empty($products)){ $tempData = [];
array_push($products,$product); $tempData['product_division'] = 'CHEMICAL';
$countNum ++; list($pCode, $packCode) = explode('-', $product->p_code);
} $tempData['productId'] = $pCode;
if($countNum == $this->apiService->getPlatformInfo('platform_params')['excelCreateLimit']){ $tempData['packageUnitDescription'] = $product->p_code;
$this->apiService->pushQueue([ $tempData['minPackageUnitDescription'] = '';
'params' => ['products' => $products,'type' => 'all'], $tempData['price'] = bcmul($product->p_price, 0.5, 2);
'consumer' => __CLASS__, $tempData['discount'] = '0.5';
'method' => 'processProductsUpdateThroughtExcel' $tempData['inCostCurrency'] = 'RMB';
],'wuxilab_product'); $tempData['status'] = $product->p_status == '1' ? 'ACTIVE' : 'INACTIVE';;
$countNum = 0; $updateProductPrice[] = $tempData;
$products = [];
} }
$result = $this->apiService->pushBatchUpdatePrice($updateProductPrice, $this->getToken());
$this->processApiResponse($result);
} }
$this->apiService->removePlatformDataEntries('wuxiLab_not_exist_products');
} }
} }
/** public function batchUpdateProductStock()
* @批量后台请求更新商品规格
* @param null $params
*/
public function batchUpdatePackagesInfo($params = null)
{ {
$token = $this->getToken(); $status = $this->apiService->checkPlatformStatus();
if($status){
$wuxiLabPackage = ['bottle','box','bp','case','ea','g','gal','hole','kg','kit','l','m','m2','mg','ml','mm','mmol','mu', $dbConnect = DB::connection('rhawn_mysql');
'ng','nmole','od','package','pair','piece','pmole','RL','sets','test', 'unit','vial','xa','µci','µg','µl','µmol'];
//$path = config('filesystems.disks.local.root').'/upload/'.$params;
//$generator = Helpers::yieldLoadCsv($path);
// yield 循环逐行读取csv内容 $startime = date('Y-m-d', strtotime('-1 day')).' 00:00:00';
/*while ($generator->valid()) { $endtime = date('Y-m-d', time()).' 00:00:00';
$content = $generator->current();
if(in_array($content[1],$wuxiLabPackage)){
$this->apiService->pushBatchUpdatePackages([
'unit_quantity' => $content[0], 'unit_type' => $content[1], 'unit_description' => $content[0].$content[1]
],$token);
}
usleep(30000);
$generator->next();
}*/
$packageList = $this->apiService->getPackageList($token);
$packagesUnit = $this->rhawnChemicalsService->getProductPackagesThroughGroupByPackUnit(); $product = $dbConnect->table('prochange')
->whereRaw("updatetime >=".strtotime($startime)." and updatetime <=".strtotime($endtime))
->where('type', '1')
->get()->toArray();
if(count($product) > 0){
$productIds = array_unique(array_column($product, 'p_id'));
$productList = $this->rhawnChemicalsService->getProductsListThroughPids($productIds);
foreach($packagesUnit as $package){ $updateProductStock = [];
if(!empty($packageList)){ foreach($productList as $product){
$exist = 0; $tempData = [];
foreach($packageList as $p){ $tempData['product_division'] = 'CHEMICAL';
$name = $package['p_pack'].$package['p_pack_unit']; list($pCode, $packCode) = explode('-', $product->p_code);
if($name == $p['unitDescription']){ $tempData['productId'] = 'R003250';//$pCode;
$exist = 1; $tempData['packageUnitDescription'] = 'R003250-1ml';//$product->p_code;
} $tempData['packageStockQuantity'] = $product->p_stock;
} $tempData['packageStockLocation'] = 'CN-SH';
if(!$exist){ $tempData['stockStatus'] = $product->p_status == '1' ? 'ACTIVE' : 'INACTIVE';;
//转换 $updateProductStock[] = $tempData;
$package['p_pack_unit'] = strtolower($package['p_pack_unit']); break;
switch($package['p_pack_unit']){
case 'ul' : $package['p_pack_unit'] = 'µl';break;
case 'ug' : $package['p_pack_unit'] = 'µg';break;
}
if(!in_array($package['p_pack_unit'],$wuxiLabPackage)){
SimpleLogs::writeLog('unit_description:'.$package['p_pack'].strtolower($package['p_pack_unit']).'规格不在范围内,跳过', __CLASS__.':batchUpdatePackagesInfo');
continue;
}
try{
//如果包装数量不是数字,跳过
if(is_numeric($package['p_pack'])){
SimpleLogs::writeLog('unit_quantity:'.$package['p_pack'].' unit_type:'.strtolower($package['p_pack_unit']).' unit_description:'.$package['p_pack'].strtolower($package['p_pack_unit']), __CLASS__.':batchUpdatePackagesInfo');
$this->apiService->pushBatchUpdatePackages([
'unit_quantity' => $package['p_pack'], 'unit_type' => strtolower($package['p_pack_unit']), 'unit_description' => $package['p_pack'].strtolower($package['p_pack_unit'])
],$token);
}else{
SimpleLogs::writeLog('unit_description:'.$package['p_pack'].strtolower($package['p_pack_unit']).'数量不是数字,跳过', __CLASS__.':batchUpdatePackagesInfo');
continue;
}
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':batchUpdatePackagesInfo', 'error');
}
} }
$result = $this->apiService->pushBatchUpdateStock($updateProductStock, $this->getToken());
$this->processApiResponse($result);
} }
} }
} }
/** public function queueBatchUpdatePackagesToApi($updateData)
* @处理不存在商品的更新
* @param $params
* @return false|void
*/
public function processProductsUpdateThroughtExcel($params)
{ {
ini_set('memory_limit','3072M'); if(empty($updateData['packageList'])){
if(!isset($params['products']) || empty($params['products'])){
return false; return false;
} }
try{ try{
$rawsList = $newPackages = []; $packageList = [];
$slice_array_length= 500; foreach($updateData['packageList'] as $packageCode => $data){
$current_length = 0; $tempData = [];
while(true){ $tempData['product_division'] = 'CHEMICAL';
$list = []; $tempData['productId'] = $data['r_code'];
$product = array_slice($params['products'],$current_length,$slice_array_length); $tempData['status'] = $data['p_status'] == '1' ? 'ACTIVE' : 'INACTIVE';
$list = $this->rhawnChemicalsService->getChemicalRawThroughtCode($product); $tempData['packageUnitDescription'] = $packageCode;
if($list){ $packageList[] = $tempData;
$rawIdList = [];
foreach ($list as $raw){
$rawIdList[] = $raw['r_id'];
}
$rawsList = array_merge($rawsList,$list);
$packages = $this->rhawnChemicalsService->getChemicalPackage($rawIdList);
if($packages){
foreach($packages as $pack){
//符合110状态才上架
if($pack['p_status'] == 1 && $pack['p_show'] == 1 && $pack['p_if_big'] == 0){
$newPackages[$pack['p_code']] = $pack;
}
}
}
}
if($current_length >= $this->apiService->getPlatformInfo('platform_params')['excelCreateLimit']){
break;
}
$current_length += $slice_array_length;
} }
if($params['type'] == 'all'){ $result = $this->apiService->pushBatchUpdatePackages($packageList, $this->getToken());
$productPath = app(WuxiLabExport::class)->saveExcel( $this->processApiResponse($result);
['rawList' => $rawsList,'packageList' => $newPackages],
'product'
);
if($productPath){
list($file,$expend) = explode('.',$productPath);
$newPath = $file.'.'.strtolower($expend);
$cmd = 'mv '.storage_path('app/'.$productPath).' '.storage_path('app/'.$newPath);
trim(shell_exec("$cmd 2>&1"));
$filePathList = explode('/',$file);
$fileName = $filePathList[count($filePathList) - 1];
$result = $this->apiService->pushBatchUploadFile('product',$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');
}
}
$packagePath = app(WuxiLabExport::class)->saveExcel(
['rawList' => $rawsList,'packageList' => $newPackages],
'package'
);
if($packagePath){
list($file,$expend) = explode('.',$packagePath);
$newPath = $file.'.'.strtolower($expend);
$cmd = 'mv '.storage_path('app/'.$packagePath).' '.storage_path('app/'.$newPath);
trim(shell_exec("$cmd 2>&1"));
$filePathList = explode('/',$file);
$fileName = $filePathList[count($filePathList) - 1];
$result = $this->apiService->pushBatchUploadFile('product',$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');
}
}
}else{
$path = app(WuxiLabExport::class)->saveExcel(
['rawList' => $rawsList,'packageList' => $newPackages],
$params['type']
);
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->apiService->backgroundLogin());
if($result){
$cmd = 'rm -rf '.storage_path('app/'.$newPath);
trim(shell_exec("$cmd 2>&1"));
SimpleLogs::writeLog('文件名为:'.$fileName.'路径:'.$newPath.'药明康德后台上传完成', __CLASS__.':processNotExistProductsUpdate');
}
}
}
usleep(rand(1000000,5000000));
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':processNotExistProductsUpdate', 'error');
}
}
/** }catch(\Throwable $exception){
* 批量更新商品包装 SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':batchUpdateToWuxiLab', 'error');
*/ var_dump($exception->getMessage());
public function batchUploadPackages()
{
$storeEntries = [];
$storeEntries = $this->apiService->getPlatformDataEntries('wuxiLab_do_not_update_products','data_values');
if(isset($storeEntries['products']) && !empty($storeEntries['products'])){
$countNum = 0;
$products = [];
foreach($storeEntries['products'] as $product){
if(!in_array($product,$products) || empty($products)){
array_push($products,$product);
$countNum ++;
}
if($countNum >= $this->apiService->getPlatformInfo('platform_params')['excelCreateLimit']){
$this->apiService->pushQueue([
'params' => ['products' => $products,'type' => 'package'],
'consumer' => __CLASS__,
'method' => 'processProductsUpdateThroughtExcel'
],'wuxilab_package');
$countNum = 0;
$products = [];
}
}
$this->apiService->removePlatformDataEntries('wuxiLab_do_not_update_products');
} }
} }
...@@ -346,93 +192,71 @@ class WuxiLabNewService ...@@ -346,93 +192,71 @@ class WuxiLabNewService
* @批量更新商品 * @批量更新商品
* @param $updateData * @param $updateData
*/ */
public function batchUpdateTo($updateData) public function queueBatchUpdateProductToApi($updateData)
{ {
if(empty($updateData['rawList'])){ if(empty($updateData['rawList']) || empty($updateData['packageList'])){
return false;
}
if(empty($updateData['packageList'])){
return false; return false;
} }
try{ try{
$result = $this->apiService->pushBatchUpdateProduct($updateData); $noSmiles = [];
if($result){ foreach($updateData['rawList'] as $data){
//处理更新不成功的商品 if(empty($data['c_smiles']) && !empty($data['c_cas'])){
if(!empty($result['errorProduct'])){ $noSmiles[] = $data['c_cas'];
$storeEntries = $this->apiService->getPlatformDataEntries('wuxiLab_not_exist_products','data_values');
if(isset($storeEntries) && !empty($storeEntries)){
if(count($storeEntries['products']) >= $this->apiService->getPlatformInfo('platform_params')['excelCreateLimit']){
$this->apiService->pushQueue([
'params' => ['products' => $storeEntries['products'],'type' => 'product'],
'consumer' => __CLASS__,
'method' => 'processProductsUpdateThroughtExcel'
],'wuxilab_product');
/*$this->apiService->pushQueue([
'params' => ['products' => $storeEntries['products'],'type' => 'package'],
'consumer' => __CLASS__,
'method' => 'processProductsUpdateThroughtExcel'
],'wuxilab_package');*/
$this->apiService->removePlatformDataEntries('wuxiLab_not_exist_products');
/*SimpleKafka::produerSend(
[
'params' => ['products' => $storeEntries['products'],'type' => 'product'],
'consumer' => __CLASS__,
'method' => 'processProductsUpdateThroughtExcel'
]
);*/
$storeEntries = [];
}
}
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'); $updateData['rawList'] = array_column($updateData['rawList'], null, 'c_cas');
if(isset($storeEntries) && !empty($storeEntries)){
if(!is_null($storeEntries) && count($storeEntries['products']) >= $this->apiService->getPlatformInfo('platform_params')['excelCreateLimit']){ if(!empty($noSmiles)){
$this->apiService->pushQueue([ $noSmiles = array_unique($noSmiles);
'params' => ['products' => $storeEntries['products'],'type' => 'package'], $baikeMysql = DB::connection('baike_mysql');
'consumer' => __CLASS__, $casResult = $baikeMysql->table('tp_mol_data')->whereIn('cas', $noSmiles)->get()->toArray();
'method' => 'processProductsUpdateThroughtExcel' if($casResult){
],'wuxilab_package'); foreach($casResult as $cas){
$this->apiService->removePlatformDataEntries('wuxiLab_do_not_update_products'); $updateData['rawList'][$cas->cas]['c_smiles'] = $cas->smiles;
$storeEntries = [];
} }
} }
$updateSuccessStoreEntries = $this->apiService->getPlatformDataEntries('wuxiLab_update_success_products','data_values'); }
//更新成功的商品
foreach($result['successProduct'] as $successProduct){ $result = $this->apiService->pushBatchUpdateProduct($updateData, $this->getToken());
if(!is_null($storeEntries) && !empty($storeEntries['products'])){ $this->processApiResponse($result);
if(!in_array($successProduct,$storeEntries['products'])){
array_push($storeEntries['products'],$successProduct); }catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':batchUpdateToWuxiLab', 'error');
var_dump($exception->getMessage());
}
}
protected function processApiResponse($apiResponse)
{
if($apiResponse){
//处理更新不成功的商品
if(!empty($apiResponse['errorProduct'])){
$errorProductsList = $this->apiService->getPlatformDataEntries('wuxiLab_error_products','data_values');
foreach($apiResponse['errorProduct'] as $errorProduct){
if(!is_null($errorProductsList) && !empty($errorProductsList['products'])){
if(!in_array($errorProduct['data'],$errorProductsList['products'])){
array_push($errorProductsList['products'],$errorProduct['data']);
} }
}else{ }else{
$storeEntries['products'][] = $successProduct; $errorProductsList['products'][] = $errorProduct['data'];
} }
if(!is_null($updateSuccessStoreEntries) && !empty($updateSuccessStoreEntries['products'])){ }
if(!in_array($successProduct,$updateSuccessStoreEntries['products'])){ $this->apiService->storePlatformDataEntries('wuxiLab_error_products',['products' => $errorProductsList['products']]);
array_push($updateSuccessStoreEntries['products'],$successProduct); }
if(!empty($apiResponse['errorPackage'])) {
$errorPackagesList = $this->apiService->getPlatformDataEntries('wuxiLab_error_packages', 'data_values');
//更新成功的商品
foreach ($apiResponse['errorPackage'] as $errorPackage) {
if (!is_null($errorPackagesList) && !empty($errorPackagesList['products'])) {
if (!in_array($errorPackage['data'], $errorPackagesList['products'])) {
array_push($errorPackagesList['products'], $errorPackage['data']);
} }
}else{ } else {
$updateSuccessStoreEntries['products'][] = $successProduct; $errorPackagesList['products'][] = $errorPackage['data'];
} }
} }
$this->apiService->storePlatformDataEntries('wuxiLab_do_not_update_products',['products' => $storeEntries['products']]); $this->apiService->storePlatformDataEntries('wuxiLab_error_packages', ['products' => $errorPackagesList['products']]);
$this->apiService->storePlatformDataEntries('wuxiLab_update_success_products',['products' => $updateSuccessStoreEntries['products']]);
} }
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':batchUpdateToWuxiLab', 'error');
var_dump($exception->getMessage());
} }
} }
...@@ -442,68 +266,18 @@ class WuxiLabNewService ...@@ -442,68 +266,18 @@ class WuxiLabNewService
*/ */
public function getToken(){ public function getToken(){
try{ try{
$token = $this->apiService->getPlatformDataEntries('wuxilab_backlogin_token','data_values'); $token = $this->apiService->getPlatformDataEntries('wuxilab_token','data_values');
if(empty($token)){ if(empty($token) || (time() > $token['ttl'])){
$apiToken = $this->apiService->backgroundLogin(); $token = $this->apiService->getToken();
if($apiToken){ if($token && $token['code'] == 200){
$backloginToken = []; $this->apiService->storePlatformDataEntries('wuxilab_token',['token' => $token['data'], 'ttl' => strtotime('+2 hour')]);
$backloginToken['currentTime'] = time(); return $token['data'];
$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('wuxilab_backlogin_token',$apiToken);
return $apiToken['token'];
}
}
return $token['token'];
} }
return $token['token'];
}catch(\Exception $exception){ }catch(\Exception $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':token error', 'error'); SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':token error', 'error');
return false; return false;
} }
} }
/**
* @初始化生成产品excel文档
* @param $exportLimit
*/
public function initCreateProductsToExcel($exportLimit)
{
$limit = $exportLimit;
$page = 0;
while(true) {
$rawList = $this->rhawnChemicalsService->getRawsList($page * $limit, $limit);
if (!$rawList) {
break;
}
$rawIdList = [];
foreach ($rawList as $raw) {
$rawIdList[] = $raw['r_id'];
}
$packages = $this->rhawnChemicalsService->getChemicalPackage($rawIdList);
$newPackages = [];
if($packages){
foreach($packages as $pack){
$newPackages[$pack['r_code']] = $pack;
}
}
if(!empty($rawList)){
app(WuxiLabExport::class)->saveExcel(
['rawList' => $rawList,'packageList' => $newPackages]
);
}
break;
}
}
} }
...@@ -107,6 +107,22 @@ return [ ...@@ -107,6 +107,22 @@ return [
'timezone' => env('CHEMSITE_DB_TIMEZONE', '+00:00'), 'timezone' => env('CHEMSITE_DB_TIMEZONE', '+00:00'),
], ],
'baike_mysql' => [
'driver' => 'mysql',
'host' => env('BAIKE_DB_HOST', '127.0.0.1'),
'port' => env('BAIKE_DB_PORT', 3306),
'database' => env('BAIKE_DB_DATABASE', 'forge'),
'username' => env('BAIKE_DB_USERNAME', 'forge'),
'password' => env('BAIKE_DB_PASSWORD', ''),
'unix_socket' => env('BAIKE_DB_SOCKET', ''),
'charset' => env('BAIKE_DB_CHARSET', 'utf8mb4'),
'collation' => env('BAIKE_DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => env('BAIKE_DB_PREFIX', ''),
'strict' => env('BAIKE_DB_STRICT_MODE', true),
'engine' => env('BAIKE_DB_ENGINE', null),
'timezone' => env('BAIKE_DB_TIMEZONE', '+00:00'),
],
'pgsql' => [ 'pgsql' => [
'driver' => 'pgsql', 'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'), 'host' => env('DB_HOST', '127.0.0.1'),
......
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