| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\modules\admin\models\jushuitan;
- use app\models\Option;
- use app\constants\OptionSetting;
- use app\models\AccountLog;
- use app\models\User;
- use app\models\SaasUser;
- use app\models\Cat;
- use app\models\Goods;
- use app\models\Supplier;
- use app\models\Attr;
- use app\models\AttrGroup;
- use app\modules\admin\models\GoodsForm;
- use app\models\GoodsCat;
- use app\models\Order;
- use app\models\OrderRefund;
- use app\models\OrderDetail;
- use app\models\Store;
- use app\models\common\CommonOrder;
- use app\modules\client\models\v1\BindForm;
- use app\modules\client\models\v1\ShareMoneyForm;
- use app\modules\client\models\OrderComplete;
- use app\models\UserShareLog;
- use app\models\Share;
- use app\models\UserShareMoney;
- use app\models\UserBindLog;
- use app\models\Level;
- use zmoyi\JuShuiTan\Auth\Auth;
- use zmoyi\JuShuiTan\Api\ApiRequest;
- use zmoyi\JuShuiTan\Api\Common\ServeHttp;
- use zmoyi\JuShuiTan\Api\Common\Util;
- use app\modules\admin\models\SupplierForm;
- use app\modules\admin\models\PlatformForm;
- class JuShuiTanForm extends Model
- {
- public static $baseUrl = 'https://openapi.jushuitan.com/'; //https://openapi.jushuitan.com/ https://dev-api.jushuitan.com/
- public static $baseUrlDev = 'https://dev-api.jushuitan.com/';
- public static $confs = [];
- public $store_id;
- public static $store_type = 'store';
- const STORE_TYPE_STORE = 'store';
- const STORE_TYPE_SUPPLIER = 'supplier';
- public static function initStoreType($type = null) {
- $type && self::$store_type = $type;
- }
- public static function decodeState($state = '{"type":"store","id":0}') {
- $res = json_decode($state, true);
- return $res;
- }
- public static function encodeState($id = 0, $type = 'store') {
- $res = json_encode(['type' => $type, 'id' => $id]);
- return $res;
- }
- public static function decodeOrderNo($orderNo) {
- $supplierOrderNo = [
- 'OR',
- 'PO',
- ];
- $orderNoHead = substr($orderNo, 0, 2);
- if(in_array($orderNoHead, $supplierOrderNo)){
- return self::STORE_TYPE_SUPPLIER;
- }
- return self::STORE_TYPE_STORE;
- }
- public static function orderStatusKey2Jst($status) {
- /**
- * 等待买家付款=WAIT_BUYER_PAY,
- * 等待卖家发货=WAIT_SELLER_SEND_GOODS(传此状态时实际支付金额即pay节点支付金额=应付金额ERP才会显示已付款待审核),
- * 等待买家确认收货=WAIT_BUYER_CONFIRM_GOODS,
- * 交易成功=TRADE_FINISHED,
- * 付款后交易关闭=TRADE_CLOSED,
- * 付款前交易关闭=TRADE_CLOSED_BY_TAOBAO;
- */
- $arr = [
- // Order::ORDER_FLOW_DEFAULT => 'WAIT_BUYER_PAY',
- Order::ORDER_FLOW_NO_SEND => 'WAIT_SELLER_SEND_GOODS',
- Order::ORDER_FLOW_SEND => 'WAIT_BUYER_CONFIRM_GOODS',
- Order::ORDER_FLOW_CONFIRM => 'TRADE_FINISHED',
- Order::ORDER_FLOW_CANCEL => 'TRADE_CLOSED',
- ];
- return $arr[$status] ?? '';
- }
-
- public static function api($store_id, $serveHttp, $params) {
- $config = self::conf($store_id);
- $apiRequest = new ApiRequest($config);
- $response = $apiRequest->request($serveHttp, $params);
- if(isset($response['code'])){
- if($response['code'] == 100){
- debug_log(['code==100', $response, $store_id], __CLASS__ . '.log');
- self::setConfExpires($store_id);
- }
- }
- return $response;
- }
- public static function setConfExpires($store_id = 0) {
- $token = Option::get(OptionSetting::JU_SHUI_TAN_TOKEN, $store_id, self::$store_type)['value'];
- if($token){
- $token = json_decode($token, true);
- $token['expires_in'] = time() - $token['refresh_time'];
- self::saveToken($store_id, $token);
- }
- }
- public static function conf($store_id = 0, $refresh = 0) {
- $cacheK = $store_id . self::$store_type;
- if(isset(self::$confs[$cacheK]) && !$refresh){
- return self::$confs[$cacheK];
- }
- $conf = Option::get(OptionSetting::JU_SHUI_TAN, 0, 'saas')['value'];
- if($conf){
- $conf = json_decode($conf, true);
- $conf['baseUrl'] = self::$baseUrl;
- if(strpos($_SERVER['SCRIPT_FILENAME'], 'quanqudao.we10.cn')){
- $conf['baseUrl'] = self::$baseUrlDev;
- }
- $url_callback = '';
- if (\Yii::$app instanceof \yii\web\Application){
- $url_callback = \Yii::$app->request->hostInfo . '/index.php/jushuitan/callback';
- }
- $conf['url_callback'] = $url_callback;
- $access_token = '';
- $refresh_token = '';
- $token = Option::get(OptionSetting::JU_SHUI_TAN_TOKEN, $store_id, self::$store_type)['value'];
- if($token){
- $token = json_decode($token, true);
- $expires = $token['expires_in'] + $token['refresh_time'] < time();
- if($token['access_token'] && !$expires){
- $access_token = $token['access_token'];
- $refresh_token = $token['refresh_token'];
- }
- if($token['is_debug']){
- $conf['baseUrl'] = self::$baseUrlDev;
- }
- }
- $conf['access_token'] = $access_token;
- $conf['refresh_token'] = $refresh_token;
- $conf['token_info'] = $token;
- $conf['__'] = [
- '$store_type' => self::$store_type,
- '$store_id' => $store_id,
- ];
- }
- self::$confs[$cacheK] = $conf;
- return $conf;
- }
-
- public static function saveConf($store_id = 0, $config = []) {
- $oldConf = Option::get(OptionSetting::JU_SHUI_TAN_TOKEN, $store_id, self::$store_type, '{}')['value'];
- $oldConf = json_decode($oldConf, true);
- $conf = array_merge($oldConf, $config);
- $set = Option::set(OptionSetting::JU_SHUI_TAN_TOKEN, json_encode($conf), $store_id, self::$store_type);
- self::conf($store_id, 1);
- return $set;
- }
-
- public static function saveToken($store_id = 0, $refreshToken = []) {
- $refreshToken['refresh_time'] = time();
- return self::saveConf($store_id, $refreshToken);
- }
- public static function getConf($store_id = 0, $key = '') {
- $config = self::conf($store_id);
- if(empty($config['token_info'])){
- return '';
- }
- return $config['token_info'][$key];
- }
- public static function code2token($store_id = 0, $code = '') {
- $config = self::conf($store_id);
- $Auth = new Auth($config);
- $refreshToken = $Auth->getAccessToken($code);
- if($refreshToken['code'] != 0){
- debug_log([__FUNCTION__, __LINE__, $store_id, $code, $refreshToken], __CLASS__ . '.log');
- return $refreshToken;
- }
-
- self::saveToken($store_id, $refreshToken['data']);
- // self::cat2Jst($store_id, 0, -1);
- return $refreshToken;
- }
- public static function refreshToken($store_id = 0) {
- if(!self::isopen($store_id)){
- return;
- }
- $config = self::conf($store_id);
- $Auth = new Auth($config);
- $refreshToken = $Auth->refreshToken($config['refresh_token']);
- debug_log([__FUNCTION__, __LINE__, $store_id, $refreshToken], __CLASS__ . '.log');
- if($refreshToken['code'] != 0){
- debug_log([__FUNCTION__, __LINE__, $store_id, $refreshToken], __CLASS__ . '.log');
- return $refreshToken;
- }
- self::saveToken($store_id, $refreshToken['data']);
- return $refreshToken;
- }
-
- public static function checkUrlSign($store_id, $get = []) {
- $config = self::conf($store_id);
- $Auth = new Auth($config);
- $sign = Util::getSign($Auth->getConfig()['app_Secret'],$get);
- if($sign == $get['sign']){
- return true;
- }
- return false;
- }
- public static function isopen($store_id = 0) {
- $config = self::conf($store_id);
- if($store_id <= 0){
- return $config;
- }
- return empty($config['access_token']) ? 0 : 1;
- }
- public static function createUrl($store_id = 0) {
- try{
- if(!self::isopen(0)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $config = self::conf($store_id);
- $Auth = new Auth($config);
- $data = [
- 'state' => self::encodeState($store_id, self::$store_type),
- 'app_key' => $Auth->getConfig()['app_Key'],
- 'timestamp' => time(),
- 'charset' => $Auth->getConfig()['charset']
- ];
- $sign = Util::getSign($Auth->getConfig()['app_Secret'],$data);
- $url = $Auth->getConfig()['authUrl'] . '?sign=' . $sign . '&' . http_build_query($data);
- return [
- 'code' => 0,
- 'data' => $url,
- ];
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
- public static function oAuth($app_key, $code, $state) {
- try{
- if($state){
- $state = self::decodeState($state);
- }
- $store_id = $state['id'];
- if($state['type'] == self::STORE_TYPE_STORE){
- $store = Store::findOne(['is_delete' => 0, 'id' => $store_id]);
- }
- if($state['type'] == self::STORE_TYPE_SUPPLIER){
- $store = Supplier::findOne(['is_delete' => 0, 'id' => $store_id]);
- }
- if (!$store || empty($app_key) || empty($code)) {
- \Yii::error('<====================>授权回调 参数错误, 参数为:' . json_encode(all_params()));
- echo '授权失败,参数错误';
- return;
- }
- self::initStoreType($state['type']);
- if(!self::checkUrlSign($store_id, all_params())){
- \Yii::error('<====================>授权回调 Sign参数错误, 参数为:' . json_encode(all_params()));
- echo '授权失败,参数错误,签名错误';
- return;
- }
- $res = self::code2token($store_id, $code);
- if ($res['code'] != 0) {
- \Yii::error('<====================> token解析失败, 参数为:' . json_encode($res));
- echo '授权失败,token解析失败,错误信息:' . $res['msg'];
- return;
- }
- echo '授权成功!';
- return;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- echo $ex->getMessage();
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function gid2Jst($id) {
- return 'cyy_' . $id;
- }
-
- public static function skuid2Jst($store_id, $goods, $goods_attr_item = []) {
- $attr_ids = array_column($goods_attr_item['attr_list'] ?? $goods_attr_item, 'attr_id');
- sort($attr_ids);
- $sku_attr_ids = implode('_', $attr_ids);
- $attrs = json_decode($goods['attr'], true);
- $sku_attr = [];
- foreach($attrs as $attr){
- $attr_ids = array_column($attr['attr_list'], 'attr_id');
- sort($attr_ids);
- $item_attr_ids = implode('_', $attr_ids);
- if($item_attr_ids === $sku_attr_ids){
- $sku_attr = $attr;
- }
- }
- // $skuRule = self::getConf($store_id, 'skuRule');
- // if($skuRule == 0){
- // return self::skuid2Jst1($goods, $sku_attr);
- // }
- // if($skuRule == 2){
- // return self::skuid2Jst2($goods, $sku_attr);
- // }
- return self::skuid2Jst2($goods, $sku_attr);
- }
-
- public static function skuid2Jst1($goods, $goods_attr_item = []) {
- $attr_ids = array_column($goods_attr_item['attr_list'] ?? $goods_attr_item, 'attr_id');
- sort($attr_ids);
- return 'cyy_' . $goods['id'] . '_' . implode('_', $attr_ids);
- }
-
- public static function skuid2Jst2($goods, $goods_attr_item = []) {
- return $goods_attr_item['no'];
- }
-
- public static function skuv2Jst($id, $goods_attr_item = []) {
- $attr_names = array_column($goods_attr_item['attr_list'] ?? $goods_attr_item, 'attr_name', 'attr_id');
- return implode(';', array_values($attr_names));
- }
-
- public static function __queryJstGoods($store_id = 0, $goods_ids = []) {
- try{
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- if(!$goods_ids){
- throw new \Exception('查询参数为空');
- }
- foreach($goods_ids as &$item){
- $item = self::gid2Jst($item);
- }
- $data = [
- 'i_ids' => $goods_ids,
- ];
- $response = self::api($store_id, ServeHttp::QUERY_MALL_ITEM,$data);
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function queryJstGoodsQty($store_id = 0, $i_ids = []) {
- try{
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $query['i_ids'] = implode(',', $i_ids);
- $response = self::api($store_id, ServeHttp::QUERY_INVENTORY,$query);
- if($response['data'] && $response['data']['inventorys']){
- foreach($response['data']['inventorys'] as &$qtyList){
- //可用数:可用数[同步线上的库存数]=主仓实际库存-订单占有数+虚拟库存+采购在途(业务设置)+进货仓(业务设置)+销退仓库存(业务设置)
- $qtyList['__online_qty'] = $qtyList['qty'] - $qtyList['order_lock'] + $qtyList['virtual_qty'] + $qtyList['purchase_qty'] + $qtyList['in_qty'] + $qtyList['return_qty'];
- if($qtyList['__online_qty'] < 0){
- $qtyList['__online_qty'] = 0;
- }
- }
- }
- $response['query'] = $query;
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function syncStoreJstGoodsQty($store_id, $goods) {
- //先更新对应云仓聚水潭商品
- if($goods->cloud_goods_id){
- $supplier = Supplier::findOne(['cloud_supplier_id' => $goods->cloud_supplier_id, 'is_delete' => 0, 'status' => 1]);
- if($supplier){
- self::syncSupplierJstGoodsQty($supplier->id, $goods->cloud_goods_id, $store_id, $goods);
- $goods->refresh();
- return;
- }
- }
-
- if(empty($goods->jst_goods_id)){
- return;
- }
- $attr_group_list = json_decode($goods->attr, true);
- if(empty($goods['jst_supplier_id'])){
- $qtyRes = self::queryJstGoodsQty($store_id, [$goods['goods_no']]);
- }else{
- // $qtyRes = self::queryJstSupplierGoodsQty($store_id, $goods['jst_supplier_id'], ['style_codes' => $goods['goods_no']]);
- $jstSupplierGoods = self::queryJstSupplierGoods($store_id, $goods['goods_no']);
- if($jstSupplierGoods['code'] != 0){
- return;
- }
- $qtyRes = $jstSupplierGoods['data']['__qty'];
- }
- $qtySkus = [];
- $updateAttrList = [];
- foreach($attr_group_list as &$attr_info){
- $qty = 0;
- if($qtyRes['data']['list']){
- foreach($qtyRes['data']['list'] as $iqty){
- if($iqty['item_code'] == $attr_info['no']){
- $qty = $iqty['stock'];
- break;
- }
- }
- }
- if($qtyRes['data']['inventorys']){
- foreach($qtyRes['data']['inventorys'] as $iqty){
- if($iqty['sku_id'] == $attr_info['no']){
- $qty = $iqty['__online_qty'];
- break;
- }
- }
- }
- $lockNum = self::lockLocalJstGoodsNumGet($store_id, $goods, $attr_info);
- $qty -= $lockNum;
- if($qty != $attr_info['num']){
- $updateAttrList[] = [
- 'attr_id_list' => array_column($attr_info['attr_list'], 'attr_id'),
- 'num' => $qty - $attr_info['num'],
- ];
- $attr_info['num'] = $qty;
- }
- }
- if($updateAttrList){
- $goods->numAdd($updateAttrList, 0);
- $goods['attr'] = json_encode($attr_group_list);
- debug_log([__FUNCTION__, '更新库存',$store_id, $goods['id'], $updateAttrList, $res, self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- }else{
- debug_log([__FUNCTION__, '无需更新库存',$store_id, $goods['id'], $updateAttrList, $res, self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- }
- }
-
- public static function syncSupplierJstGoodsQty($supplier_id, $goods, $store_id = 0, $store_goods = null) {
- self::initStoreType(self::STORE_TYPE_SUPPLIER);
- if(is_int($goods) || is_string($goods)){
- $gid = $goods;
- $glist = (new PlatformForm(['id' => $gid]))->goodsInfo();
- if($glist['code'] == 0 && $glist['data']['count'] == 1){
- $goods = $glist['data']['list'][0];
- }else{
- throw new \Exception('云仓接口:' . $glist['msg']);
- }
- $goods['attr'] = $goods['attrs'];
- }
- if(empty($goods['jst_goods_id'])){
- return $goods;
- }
- $goods['__attrs'] = $goods['attrs'];
- $attr_group_list = json_decode($goods['attrs'], true);
- if(empty($goods['jst_supplier_id'])){
- $qtyRes = self::queryJstGoodsQty($supplier_id, [$goods['goods_no']]);
- }else{
- // $qtyRes = self::queryJstSupplierGoodsQty($supplier_id, $goods['jst_supplier_id'], ['style_codes' => $goods['goods_no']]);
- $jstSupplierGoods = self::queryJstSupplierGoods($supplier_id, $goods['goods_no']);
- if($jstSupplierGoods['code'] != 0){
- return;
- }
- $qtyRes = $jstSupplierGoods['data']['__qty'];
- }
- $store_goods_attr = (array)json_decode($store_goods['attr'], true);
- $updateAttrListStore = 0;
- $qtySkus = [];
- $updateAttrList = [];
- foreach($attr_group_list as &$attr_info){
- $qty = 0;
- if($qtyRes['data']['list']){
- foreach($qtyRes['data']['list'] as $iqty){
- if($iqty['item_code'] == $attr_info['no']){
- $qty = $iqty['stock'];
- break;
- }
- }
- }
- if($qtyRes['data']['inventorys']){
- foreach($qtyRes['data']['inventorys'] as $iqty){
- if($iqty['sku_id'] == $attr_info['no']){
- $qty = $iqty['__online_qty'];
- break;
- }
- }
- }
- $lockNum = self::lockLocalJstGoodsNumGet($supplier_id, $goods, $attr_info);
- $qty -= $lockNum;
- if($qty != $attr_info['num']){
- $updateAttrList[] = [
- 'attr_id_list' => array_column($attr_info['attr_list'], 'attr_id'),
- 'num' => $qty - $attr_info['num'],
- ];
- $attr_info['num'] = $qty;
- }
-
- foreach($store_goods_attr as $si => $sattr){
- if($attr_info['no'] == $sattr['no']){
- if($attr_info['num'] != $sattr['num']){
- $updateAttrListStore = 1;
- $store_goods_attr[$si]['num'] = $attr_info['num'];
- }
- break;
- }
- }
- }
- if($updateAttrListStore || $updateAttrList){
- $goods['attrs'] = json_encode($attr_group_list);
- $form = new SupplierForm();
- $res = $form->setGoodsAttrNum($supplier_id, $goods['id'], $updateAttrList, $store_id);
- debug_log([__FUNCTION__, '更新云仓库存',$supplier_id, $goods['id'], $updateAttrList, $res, self::lockLocalJstGoodsNumList($supplier_id)], __CLASS__ . '.log');
- }else{
- debug_log([__FUNCTION__, '无需更新云仓库存',$supplier_id, $goods['id'], $updateAttrList, $res, self::lockLocalJstGoodsNumList($supplier_id)], __CLASS__ . '.log');
- }
- return $goods;
- }
-
- public static function queryJstGoodsList($store_id = 0, $query = [], $get_qty = 0) {
- try{
- $get_qty = $get_qty ? $get_qty : $query['get_qty'];
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- // $query['i_ids'] = ['cyy_2621'];
- // $query['item_flds'] = ['onsale'];
- // $query['only_item'] = true;
- $query['modified_begin'] = $query['modified_begin'] ?? date('Y-m-d 00:00:00', time() - 86400 * 6);
- $query['modified_end'] = $query['modified_end'] ?? date('Y-m-d 23:59:59');
- if($query['i_ids']){
- unset($query['modified_begin']);
- unset($query['modified_end']);
- }
- $response = self::api($store_id, ServeHttp::QUERY_MALL_ITEM,$query);
- if($response['code'] == 0 && $response['data']['data_count']){
- foreach($response['data']['datas'] as &$item){
- $item['qty'] = 0;
- if($get_qty){
- $qty = self::queryJstGoodsQty($store_id, [$item['i_id']]);
- $item['__qty'] = $qty;
- }
- $item['pics'] = $item['pics'] ?? [$item['pic']];
- $item['onsale'] = 0;
- if($item['skus']){
- foreach($item['skus'] as &$v){
- $v['properties_value'] = $v['properties_value'] ? : '默认';
- if($v['enabled'] == 1){
- $item['onsale'] = 1;
- }
- $v['qty'] = 0;
- if($get_qty && $qty['data']['inventorys']){
- foreach($qty['data']['inventorys'] as $sku){
- if($v['sku_id'] == $sku['sku_id']){
- $v['qty'] = $sku['__online_qty'];
- }
- }
- }
- $item['qty'] += $v['qty'];
- }
- }
- $item['_attr'] = self::handleAttr($item);
- }
- }
- $response['query'] = $query;
- $response['_args'] = func_get_args();
- $response['$get_qty'] = $get_qty;
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function queryJstGoods($store_id = 0, $i_id = '') {
- $query['i_ids'] = [$i_id];
- $list = self::queryJstGoodsList($store_id, $query, 1);
- if($list['code'] != 0){
- return $list;
- }
- if($list['data']['datas']){
- return [
- 'code' => 0,
- 'data' => $list['data']['datas'][0],
- ];
- }
- return [
- 'code' => 1,
- 'msg' => '商品未查到1',
- ];
- }
-
- public static function queryJstSupplierGoodsList($store_id = 0, $jst_supplier_name = '', $query = [], $get_goods_info = 0, $get_qty = 0) {
- try{
- $get_qty = $get_qty ? $get_qty : $query['get_qty'];
- $get_goods_info = $get_goods_info ? $get_goods_info : $query['get_goods_info'];
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $query['page_num'] = $query['page_num'] ?? 1;
- $query['page_size'] = $query['page_size'] ?? 20; //每页条数 最多100
- $query['sort'] = 'DESC';
- // $query['creator'] = '创建人';
- // $query['style_code_list'] = ['cyy_2621']; //款号列表 精确搜索,一次最多20个
- // $query['item_code_list'] = ['cyy_2621_602']; //商品编码 精确搜索,一次最多20个
- // $query['item_name'] = '测试商品1'; //商品名称 模糊搜索
- // $query['distributor_supplier_name'] = '代发供应商名称';
- // $query['created_start_time'] = '2022-06-30 13:37:32';
- // $query['created_end_time'] = '2022-06-30 13:37:32';
- // $query['update_start_time'] = '2022-06-30 13:37:32';
- // $query['update_end_time'] = '2022-06-30 13:37:32';
- $jst_supplier_name && $query['distributor_supplier_name'] = $jst_supplier_name;
- $response = self::api($store_id, '/open/api/goods/inneropen/goods/querygoodslist',$query);
- // $response = json_decode('{"msg": null,"code": 0,"data": {"total": 126,"has_next": true,"list": [{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 7.9,"distributor_supplier_name": "湖南优点购商贸有限公司","created": "2024-03-11 12:57:55","style_code": "469865549258","item_name": "麻辣王子辣条零食网红小零食小吃批发零售独立包装休闲食品面筋","main_image_list": ["https://images.sursung.com/prod/pt/10968313/20231002/5710B7DCE9AF4838A2B241272C02DDA6_s182221_h800_w800.jpg","https://images.sursung.com/prod/pt/10968313/20231002/B51B392CDD5B4F26AF01DA4B5778CE29_s164513_h800_w800.jpg","https://images.sursung.com/prod/pt/10968313/20231002/2048ABE808B64640B6CC3C5EB5F2AFC9_s220785_h800_w800.jpg","https://images.sursung.com/prod/pt/10968313/20231002/58ED2CB6301345088CD75918D9628D5E_s144894_h800_w800.jpg","https://images.sursung.com/prod/pt/10968313/20231002/0F7409C0B4634758AF650BF412E53B92_s146490_h800_w800.jpg"],"min_cost_price": null,"item_spu_id": "C10592F30B0A4A63BD38EB4C9F52E69B","item_status": "distribution","distributor_status": true,"item_source": "FROM_SUP","distributor_co_id": "10968313","private_status": true,"updated": "2024-03-11 13:37:29","min_supply_price": 5},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 49,"distributor_supplier_name": "","created": "2024-03-07 16:55:12","style_code": "24260036030","item_name": "春季新款圆领纯棉休闲刺绣套头舒适卫衣66913 | 24260036030","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/C4B461F6770D484896E5EC0A3C6C5275_s194132_h1280_w1280.jpg"],"min_cost_price": 23,"item_spu_id": "7A96FC0F898F40B2A69EE9F6B083AC54","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-08 13:33:01","min_supply_price": 28},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 49,"distributor_supplier_name": "","created": "2024-03-07 16:55:12","style_code": "24260046030","item_name": "春季新款圆领纯棉休闲刺绣套头舒适卫衣66901 | 24260046030","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/96D0A81839A2493383B91ADC7B2B341C_s211325_h1280_w1280.jpg"],"min_cost_price": 23,"item_spu_id": "825D42C894DE45D1907E590F98E24338","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-08 12:25:39","min_supply_price": 28},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 49,"distributor_supplier_name": "","created": "2024-03-07 16:55:11","style_code": "24260076030","item_name": "春季新款圆领纯棉休闲刺绣套头舒适卫衣66922 | 24260076030","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/861BF4F2E8B649CD81E65D54A3626A38_s194411_h1280_w1280.jpg"],"min_cost_price": 23,"item_spu_id": "42EE1CDE64024140847658A7268625BA","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-08 11:47:00","min_supply_price": 28},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 49,"distributor_supplier_name": "","created": "2024-03-07 16:55:11","style_code": "24260056030","item_name": "春季新款圆领纯棉休闲刺绣套头舒适卫衣66903 | 24260056030","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/7C5F67FBFA4C43B99DDD4C530F1D6264_s204319_h1280_w1280.jpg"],"min_cost_price": 23,"item_spu_id": "656BA60B3B1B4201BBDC61B8B9B218E2","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-08 11:56:08","min_supply_price": 28},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 49,"distributor_supplier_name": "","created": "2024-03-07 16:55:11","style_code": "24260066030","item_name": "春季新款圆领纯棉休闲刺绣套头舒适卫衣66915 | 24260066030","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/0CA44A67A75C4BA7BD45DBB9B8D47769_s226359_h1280_w1280.jpg"],"min_cost_price": 24,"item_spu_id": "891E32837A464C8088393E1372DB89E8","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-08 13:11:22","min_supply_price": 29},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 48,"distributor_supplier_name": "","created": "2024-03-07 16:53:36","style_code": "24230136030","item_name": "H*家西裤男斜纹竹炭纤维舒适商务休闲男裤A12 | 24230136030","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/CCBE49C37EFB4FDAB99145A9A5C9E854_s186526_h1701_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/4B4D6D4BD9254F4EA488E20205A8FB96_s190233_h1631_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/50ADE8CA42BF47F3B5CAF915522A9B9A_s193943_h1649_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/CFC060FB235A4DDA85A2451CCBE066BB_s421984_h1526_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/C88B1FFDF79B451EB75AEB66ED74A8CF_s457301_h1615_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/64D05779E5A54E9D9E1E2A4F441BFDB4_s258059_h1358_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/A386322950034DB0AA233248055C7DA5_s322777_h1356_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/43A1754A18A144EF93925FE0BBD73144_s508934_h1364_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/16B5F14917624D3B82A3E8291397DF49_s215763_h685_w1260.jpg"],"min_cost_price": 21,"item_spu_id": "4D630D58552848D2ACFFFDAF2554A449","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-08 11:37:33","min_supply_price": 26},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 79,"distributor_supplier_name": "","created": "2024-03-07 16:53:36","style_code": "24310416060","item_name": "H*家夹克男双面穿字母印花抽绳连帽工装顺滑外套男春季AVA | 24310416060","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/22423970A6DF42CF9A7CCA819E5C2038_s242182_h1378_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/4911439C485B4135BFB3703300ADF4FF_s205627_h1349_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/1286A3354E8E41BCB208B3FB40197A6B_s465277_h1398_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/4DAA39ED00604448BB31C7698CB91C8E_s96942_h667_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/A43161123E8144B4B44B4544330B11A0_s335129_h1281_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/BDDA2A2EE0934C3BBCE62BF66AB6EEB1_s510854_h1491_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/3C4FD4D970AE407CB0B5EFF8ED05275D_s450168_h2058_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/EF3CF4CDEC914E30A2DDECD4AEA14A0B_s148401_h846_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/0F7F1CA22F4B4470B86348E0FB4AF0C6_s290693_h944_w1260.jpg"],"min_cost_price": 50,"item_spu_id": "A40E0BC49E7B480A98B0CE062F244EAE","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-07 18:03:35","min_supply_price": 55},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 48,"distributor_supplier_name": "","created": "2024-03-07 16:53:36","style_code": "24230146036","item_name": "H*家休闲裤男夏季抽绳松紧腰裤腿字母运动九分裤TER | 24230146036","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240307/3926F792AAEC4D1A8790CCCE1E337024_s72042_h1274_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/657759FD9120435EA6BAB2E866D6811A_s74270_h1293_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/088CD4CB2C2F467183791EC23628CB25_s238601_h1227_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/D51C4AAAA407439991DEBE965F95B09E_s247025_h1151_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/42D9A6FC263148EAA4AECE7A9CD3E80D_s222941_h1462_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/EDC20AE52B9C4A11A5572B38B99272B7_s187824_h1483_w1260.jpg","https://images.sursung.com/prod/item/13492662/20240307/67B778C72CF64F6F84A989F6E1AE0E55_s313012_h1134_w1260.jpg"],"min_cost_price": 27,"item_spu_id": "F9705E8AEC2F487A9945EA5B64E16D45","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-08 10:41:36","min_supply_price": 32},{"perfect_platform_list": [{"perfect": true,"platform_type": "taobao"}],"creator": "徐银","min_sale_price": 139,"distributor_supplier_name": "","created": "2024-03-04 11:32:07","style_code": "2431016095","item_name": "春季专柜同步款翻领外套净色时尚休闲男暗扣夹克外套ZK8922 | 2431016095","main_image_list": ["https://images.sursung.com/prod/item/13492662/20240304/3A37A5B2262244F2B2CA96DF68F4CBFB_s311700_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/7311EFD7A64F4891ACCA55944A058A14_s320340_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/1A55E5BA63544FEE9B6B062179236794_s533254_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/5A5D0AA5EC024BB39B9AA020D67BB797_s566833_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/69406076596F4CBD884CD2EC5CBC2F98_s575510_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/91F1ACA69FF84436B53B141058BFCB3E_s577732_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/328B235BB6C54D56BDD374D1C26BC672_s499824_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/2D1D3CBB2F824BE886CFD2E5C9A22C2B_s364101_h1536_w1536.jpg","https://images.sursung.com/prod/item/13492662/20240304/0B7514E9F91D49A7BE5F571E57F5A86A_s202425_h995_w1260.jpg"],"min_cost_price": 85,"item_spu_id": "294A875FCE8A419E90CEB72721461527","item_status": "distribution","distributor_status": false,"item_source": "ERP_SPU","distributor_co_id": null,"private_status": true,"updated": "2024-03-04 13:58:21","min_supply_price": 90}]},"request_id": "c2d5c993a3f4432e89e3b0d5db561bb9","query": {"page_num": "1","page_size": "10","sort": "DESC"},"_args": [1,{"page_num": "1","page_size": "10","sort": "DESC"},null],"$get_qty": null}', true);
- if($response['code'] == 0 && $response['data']['total']){
- foreach($response['data']['list'] as &$item){
- $style_code = $item['style_code'];
- $supplier_co_id = 0;
- if($item['distributor_status']){
- $supplier_co_id = $item['distributor_co_id'];
- }
- $item['_supplier_co_id'] = $supplier_co_id;
- $item['onsale'] = 0;
- if($item['item_status'] == 'distribution' && $item['private_status'] == false){
- $item['onsale'] = 1;
- }
- $item['qty'] = 0;
- $item['__qty'] = [];
- $item['__goods_info'] = [];
- if($get_goods_info){
- $item['__goods_info'] = self::queryJstSupplierGoodsInfo($store_id, $item['item_spu_id']);
- $ginfo = $item['__goods_info']['data'];
- if($get_qty && $ginfo['item_sku_list']){
- if($supplier_co_id){
- $item_codes = array_column($ginfo['item_sku_list'], 'item_code');
- $item['__qty'] = self::queryJstSupplierGoodsQty($store_id, $supplier_co_id, ['item_codes' => implode(',', $item_codes)]);
- }else{
- $item['__qty'] = self::queryJstGoodsQty($store_id, [$style_code]);
- }
- $item['_attr'] = self::supplierGoodsHandleAttr($item);
- foreach($item['_attr'] as &$v){
- $item['qty'] += $v['num'];
- }
- }
- }
- }
- }
- $response['$store_type'] = self::$store_type;
- $response['getConf'] = self::getConf($store_id);
- $response['query'] = $query;
- $response['_args'] = func_get_args();
- $response['$get_qty'] = $get_qty;
- $response['$get_goods_info'] = $get_goods_info;
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function queryJstSupplierGoodsInfo($store_id = 0, $item_spuId = '') {
- try{
- $k = [$store_id, $item_spuId];
- $v = cache()->get($k);
- if($v){
- return $v;
- }
- $query['item_spuId'] = $item_spuId;
- $response = self::api($store_id, '/open/api/goods/inneropen/goods/querygoodsdetail',$query);
-
- $response['query'] = $query;
- cache()->set($k, $response, 3600);
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function queryJstSupplierGoodsQty($store_id = 0, $supplier_co_id = 0, $query = []) {
- try{
- $query['supplier_co_id'] = $supplier_co_id;
- // $query['style_codes'] = $style_code;
- // $query['item_codes'] = $item_code;
- $query['page_num'] = $query['page_num'] ?? 1;
- $query['page_size'] = $query['page_size'] ?? 500; //每页条数 最多500
- $query['order_by_key'] = $query['order_by_key'] ?? 1;
- $response = self::api($store_id, '/open/api/goods/inneropen/supplier/goods/querydiserpgoodsdata',$query);
-
- $response['query'] = $query;
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function queryJstSupplierGoods($store_id = 0, $style_code = '') {
- $query['style_code_list'] = [$style_code];
- $list = self::queryJstSupplierGoodsList($store_id, '', $query, 1, 1);
- if($list['code'] != 0){
- return $list;
- }
- if($list['data']['list']){
- return [
- 'code' => 0,
- 'data' => $list['data']['list'][0],
- ];
- }
- return [
- 'code' => 1,
- 'msg' => '商品未查到',
- 'data' => $list,
- ];
- }
-
- public static function queryJstSupplierList($store_id = 0, $query = []) {
- try{
- $query['status'] = 2;
- $query['page_num'] = $query['page_num'] ?? 1;
- $query['page_size'] = $query['page_size'] ?? 100; //每页数量,最大100
- $response = self::api($store_id, '/open/api/company/inneropen/partner/channel/querymysupplier',$query);
-
- $response['query'] = $query;
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function goods2Jst($store_id = 0, $start_id = 0, $count = 1, $upType = 0) {
- try{
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $upload_goods = self::getConf($store_id, 'upload_goods');
- if(!$upload_goods){
- return [
- 'code' => 1,
- 'msg' => 'upload_goods close',
- ];
- }
- $query = Goods::find()->where(['>=', 'id', $start_id])->orderBy('id ASC');
- $query->andWhere(['store_id' => $store_id, 'is_delete' => 0]);
-
- $cacheKey = 'goods2Jst' . $store_id;
- if($count == -1){
- $count = $query->count();
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- throw new \Exception('已有队列进行中,请在' . ($cacheV - time()) . '秒后重试');
- }
- }
- if($count > 1){
- $time = round($count * 1.5);
- cache()->set($cacheKey, time() + $time, $time);
- }
-
- $icount = 5;
- $icount = $count < $icount ? $count : $icount;
- $list = $query->limit($icount)->all();
- $max = 50;
- $data = [];
- $upcount = 0;
- $upGoodsIds = [];
- foreach($list as $item){
- $c_name = null;
- $goods_cat = GoodsCat::findOne([ 'goods_id' => $item['id'], 'is_delete' => 0 ]);
- if($goods_cat){
- $cat = Cat::findOne($goods_cat->cat_id);
- $c_name = self::cname2Jst($cat);
- }
- // $supplier = Supplier::findOne(['cloud_supplier_id'=>$item['cloud_supplier_id']]);
- $_data = [
- 'batch_enabled' => false,
- 'i_id' => self::gid2Jst($item->id),
- 'name' => $item->name,
- 'pic' => $item->cover_pic,
- 'unit' => $item['unit'],
- 'weight' => $item['weight'],
- 'enabled' => $item['status'] == 1 ? 1 : -1,
- 'c_price' => $item['cost_price'],
- // 'supplier_name' => $supplier->supplier_name ?: '',
- // 'supplier_i_id' => $item['cloud_goods_id'],
- ];
- $c_name && $_data['c_name'] = $c_name;
- $skus = json_decode($item->attr, true);
- if($upcount && (count($data) + count($skus) >= $max)){
- break;
- }
- foreach(array_slice($skus, 0, 50) as $sku){
- $sku_id = self::skuid2Jst($store_id, $item, $sku);
- $sku_name = self::skuv2Jst($item->id, $sku);
- $_data = array_merge($_data, [
- 'sku_id' => $sku_id,
- 's_price' => $sku['price'],
- 'sku_pic' => $sku['pic'] ?: $item['cover_pic'],
- 'sku_code' => $sku['no'],
- 'qty' => $sku['num'],
- 'properties_value' => $sku_name,
- ]);
- $data[] = $_data;
- }
- $upcount++;
- $upGoodsIds[] = $item->id;
- $start_id = $item->id;
- if(count($data) >= $max){
- break;
- }
- }
- if($upType == 0){
- $updata = [
- 'items' => $data,
- ];
- $response = self::api($store_id, ServeHttp::UPLOAD_ITEMSKU, $updata);
- if($response['code']){
- debug_log(['goods2Jst', $response, $upGoodsIds], __CLASS__ . '.log');
- }
- if(isset($response['datas'])){
- foreach($response['datas'] as $item){
- if(!$item['issuccess']){
- debug_log(['goods2Jst', $item], __CLASS__ . '.log');
- }
- }
- }
- }
- if($upType == 1){
- $updata = [
- 'items' => $data,
- 'so_id' => self::gid2Jst($item->id) . time(),
- 'warehouse' => 1,
- 'is_confirm' => 1,
- 'type' => 'check',
- ];
- $response = self::api($store_id, ServeHttp::UPLOAD_INVENTORY_V2, $updata);
- if($response['code']){
- debug_log(['goods2Jst $upType == 1', $response, $upGoodsIds], __CLASS__ . '.log');
- }
- }
- if($count > 1 && ($count - $upcount > 1)){
- $queue = queue_push(new \app\jobs\jushuitan\Goods2JSTJob([
- 'id' => $store_id,
- 'start_id' => $start_id + 1,
- 'count' => $count - $upcount,
- 'upType' => $upType,
- ]), 1);
- }
- sleep(1);
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function cname2Jst($cat, $cids = []) {
- $cname = 'cyy' . str_replace('-', '_', $cat['name']);
- if(in_array($cat['id'], $cids)){
- throw new \Exception('层级嵌套错误');
- }
- $cids[] = $cat['id'];
- if($cat['parent_id'] == 0){
- $name = $cname;
- }else{
- $pcat = Cat::findOne(['id' => $cat['parent_id'], 'is_delete' => 0]);
- if(!$pcat){
- throw new \Exception('父级已删除');
- }
- $name = self::cname2Jst($pcat, $cids) . '-' . $cname;
- }
- return $name;
- }
-
- public static function cat2Jst($store_id = 0, $start_id = 0, $count = 1) {
- try{
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $upload_goods = self::getConf($store_id, 'upload_goods');
- if(!$upload_goods){
- return [
- 'code' => 1,
- 'msg' => 'upload_goods close',
- ];
- }
- $query = Cat::find()->where(['>=', 'id', $start_id])->orderBy('id ASC');
- $query->andWhere(['store_id' => $store_id, 'is_delete' => 0]);
-
- $msgExt = '';
- $cacheKey = 'cat2Jst' . $store_id;
- if($count == -1){
- $count = $query->count();
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- throw new \Exception('已有队列进行中,大约' . ($cacheV - time()) . '秒后执行完毕');
- }
- }
- if($count > 1){
- $time = round($count * 1.5);
- cache()->set($cacheKey, time() + $time, $time);
- $msgExt = '.大约' . $time . '秒后执行完毕';
- }
-
- $query->select('id, parent_id, name, sort');
- $list = $query->limit($count == 1 ? 1 : 2)->asArray()->all();
- if(count($list)){
- $item = $list[0];
- try{
- $c_name = self::cname2Jst($item);
- } catch (\Exception $ex) {
- debug_log(['cat2Jst$c_name$del', $item], __CLASS__ . '.log');
- \Yii::error([__FUNCTION__, $ex->getMessage(), $item]);
- $c_name = null;
- }
- if($c_name){
- $data = [
- 'c_name' => $c_name,
- 'sort' => $item['sort'],
- ];
- $response = self::api($store_id, '/open/jushuitan/category/upload', $data);
- if($response['code']){
- debug_log(['cat2Jst', $response, $data], __CLASS__ . '.log');
- }
- }
- }
- if($count > 1 && count($list) > 1){
- $queue = queue_push(new \app\jobs\jushuitan\Cat2JSTJob([
- 'id' => $store_id,
- 'start_id' => $list[1]['id'],
- 'count' => $count -1,
- ]), 1);
- }
- sleep(1);
- return [
- 'code' => 0,
- 'msg' => '操作成功,后台队列处理中。' . $msgExt,
- 'data' => $response,
- ];
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function orderSingleQuery($store_id = 0, $orderNo = []) {
- if($orderNo){
- if(is_string($orderNo)){
- $orderNo = [$orderNo];
- }
- $shop_id = self::getConf($store_id, 'shop_id');
- $updata = [
- 'shop_id' => (int)$shop_id,
- 'so_ids' => $orderNo,
- ];
- $response = self::api($store_id, ServeHttp::QUERY_ORDERS_SINGLE, $updata);
- debug_log(['orderSingleQuery', $response, $orderNo, $updata], __CLASS__ . '.log');
- if($response['code']){
- debug_log(['orderSingleQuery', $response, $orderNo, $updata], __CLASS__ . '.log');
-
- }
- return $response;
- }
- return [
- 'code' => 0,
- 'msg' => '',
- ];
- }
-
- public static function orderLabelUpload($store_id = 0, $orderNo = '', $labels = [], $action_type = 1) {
- if($orderNo && $labels){
- $shop_id = self::getConf($store_id, 'shop_id');
- $updata = [
- 'shop_id' => (int)$shop_id,
- 'so_id' => (string)$orderNo,
- 'labels' => $labels,
- 'action_type' => (int)$action_type,
- ];
- $response = self::api($store_id, '/open/jushuitan/order/label/upload', $updata);
- debug_log(['orderLabelUpload', $response, $orderNo, $updata], __CLASS__ . '.log');
- if($response['code']){
- debug_log(['orderLabelUpload', $response, $orderNo, $updata], __CLASS__ . '.log');
- return $response;
- }
- }
- return [
- 'code' => 0,
- 'msg' => '',
- ];
- }
-
- public static function order2Jst($store_id = 0, $start_id = 0, $count = 1) {
- try{
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能' . json_encode(func_get_args()));
- }
- $query = Order::find()->where(['>=', 'id', $start_id])->orderBy('id ASC');
- $query->andWhere(['store_id' => $store_id, 'is_delete' => 0]);
-
- $cacheKey = 'order2Jst' . $store_id;
- if($count == -1){
- $count = $query->count();
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- throw new \Exception('已有队列进行中,请在' . ($cacheV - time()) . '秒后重试');
- }
- }
- if($count > 1){
- $time = round($count * 1.5);
- cache()->set($cacheKey, time() + $time, $time);
- }
- $shop_id = self::getConf($store_id, 'shop_id');
- if(empty($shop_id)){
- throw new \Exception('shop_id不存在,不能同步订单' . json_encode(func_get_args()));
- }
-
-
- $icount = 50;
- $icount = $count < $icount ? $count : $icount;
- $list = $query->limit($icount)->all();
- $list = array_combine(array_column($list, 'order_no'), $list);
- $max = 50;
- $data = [];
- $upcount = 0;
- $upOrderIds = [];
- foreach($list as $item){
- $need_express = 1;
- if($item['is_delivery'] || $item['is_offline']){
- $need_express = 0;
- }
- $is_cod = $item['pay_type'] == Order::PAY_TYPE_COD;
- $shop_status = self::orderStatusKey2Jst($item['trade_status']);
- if(!$shop_status && !$is_cod){
- continue;
- }
- $addres = json_decode($item['address_data'], true);
- $ods = $item->detail;
- $goodsList = [];
- foreach ($ods as $od) {
- $sku = json_decode($od->attr, true);
- $goods = json_decode($od['goods_info'], true);
- $sku_id = self::skuid2Jst($store_id, $goods, $sku);
- $sku_name = self::skuv2Jst($od->goods_id, $sku);
- $_data = [
- 'sku_id' => $sku_id,
- 'shop_sku_id' => $sku_id,
- 'amount' => (float)$od['total_price'],
- 'base_price' => (float)$od['total_price'],
- 'qty' => $od['num'],
- 'name' => $od->goods_name . '_' . $sku_name,
- 'outer_oi_id' => md5($item['order_no'] . '_' . $sku_id),
- ];
- $goodsList[] = $_data;
- }
- $_data = [
- 'shop_id' => (int)$shop_id,
- 'so_id' => $item['order_no'],
- 'order_date' => date('Y-m-d H:i:s', $item['created_at']),
- 'shop_status' => $shop_status,
- 'shop_buyer_id' => (string)$item['user_id'],
- 'receiver_state' => $addres['province'] ?? '--',
- 'receiver_city' => $addres['city'] ?? '--',
- 'receiver_district' => $addres['district'] ?? '--',
- 'receiver_address' => $addres['detail'] ?? '--',
- 'receiver_name' => $item['name'] ?? '--',
- 'receiver_phone' => $item['mobile'] ?? '--',
- 'pay_amount' => (float)$item['pay_price'],
- 'freight' => (float)$item['express_price'],
- 'buyer_message' => $item['remark'],
- 'is_cod' => $is_cod,
- 'items' => $goodsList,
- 'pay' => [
- 'outer_pay_id' => $item['order_no'],
- 'pay_date' => date('Y-m-d H:i:s', $item['pay_time']),
- 'payment' => Order::PAY_TYP_NAME[$item['pay_type']] ?? '--',
- 'seller_account' => '--',
- 'buyer_account' => (string)$item['user_id'],
- 'amount' => (float)$item['pay_price'],
- ],
- ];
- if($item['express_no']){
- $_data['l_id'] = $item['express_no'];
- $_data['logistics_company'] = $item['express'] ?: '--';
- }
- $_data['labels'][] = 'cyy';
- if($item['is_delivery']){
- $_data['labels'][] = '同城配送';
- }
- if($item['is_offline']){
- $_data['labels'][] = '自提';
- }
- if($is_cod){
- $_data['labels'][] = '货到付款';
- }
- if($item['trans_status'] == 1){
- $orderLabelUpload = self::orderLabelUpload($store_id, $item['order_no'], ['转单']);
- }
- if(!$need_express){
- $_data['l_id'] = '-';
- $_data['logistics_company'] = '其他';
- }
- $_data['labels'] = implode(',', $_data['labels']);
- $data[] = $_data;
- $upcount++;
- $upOrderIds[] = $item->id;
- $start_id = $item->id;
- if(count($data) >= $max){
- break;
- }
- }
- $updata = $data;
- if(empty($updata)){
- throw new \Exception('提交数据为空' . json_encode(func_get_args()));
- }
- self::saveConf($store_id, ['upload_order_time_last' => time()]);
- $response = self::api($store_id, ServeHttp::UPLOAD_ORDERS, $updata);
- debug_log(['order2Jst', $response, $upOrderIds, $updata], __CLASS__ . '.log');
- if($response['code']){
- debug_log(['order2Jst', $response, $upOrderIds, $updata], __CLASS__ . '.log');
- }
- if(isset($response['data']) && isset($response['data']['datas'])){
- foreach($response['data']['datas'] as $item){
- if(!$item['issuccess']){
- debug_log(['order2Jst', $item], __CLASS__ . '.log');
- }else{
- self::lockLocalJstGoodsNum($list[$item['so_id']], 1);
- }
- }
- }
- if($count > 1 && ($count - $upcount > 1)){
- $queue = queue_push(new \app\jobs\jushuitan\Order2JSTJob([
- 'id' => $store_id,
- 'start_id' => $start_id + 1,
- 'count' => $count - $upcount,
- ]), 1);
- }
- sleep(1);
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function orderRefund2Jst($store_id = 0, $start_id = 0, $count = 1) {
- try{
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能' . json_encode(func_get_args()));
- }
- $query = OrderRefund::find()->where(['>=', 'id', $start_id])->orderBy('id ASC');
- $query->andWhere(['store_id' => $store_id, 'is_delete' => 0]);
-
- $cacheKey = 'orderRefund2Jst' . $store_id;
- if($count == -1){
- $count = $query->count();
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- throw new \Exception('已有队列进行中,请在' . ($cacheV - time()) . '秒后重试');
- }
- }
- if($count > 1){
- $time = round($count * 1.5);
- cache()->set($cacheKey, time() + $time, $time);
- }
- $shop_id = self::getConf($store_id, 'shop_id');
- if(empty($shop_id)){
- throw new \Exception('shop_id不存在,不能同步订单' . json_encode(func_get_args()));
- }
-
-
- $icount = 50;
- $icount = $count < $icount ? $count : $icount;
- $list = $query->limit($icount)->all();
- $list = array_combine(array_column($list, 'order_refund_no'), $list);
- $max = 50;
- $data = [];
- $upcount = 0;
- $upOrderIds = [];
- foreach($list as $item){
- $o = Order::findOne($item['order_id']);
- $ods = $item->detail;
- $goodsList = [];
- foreach ($ods as $od) {
- $sku = json_decode($od->attr, true);
- $goods = json_decode($od['goods_info'], true);
- $sku_id = self::skuid2Jst($store_id, $goods, $sku);
- $sku_name = self::skuv2Jst($od->goods_id, $sku);
- $_data = [
- 'sku_id' => $sku_id,
- 'amount' => (float)$od['total_price'],
- 'base_price' => (float)$od['total_price'],
- 'qty' => $od['num'],
- 'type' => '退货',
- // 'name' => $od->goods_name . '_' . $sku_name,
- 'outer_oi_id' => md5($o['order_no'] . '_' . $sku_id),
- ];
- $goodsList[] = $_data;
- }
- $good_status = 'BUYER_RECEIVED';
- if($item['is_user_send']){
- $good_status = 'BUYER_RETURNED_GOODS';
- }
- if($item['status'] == 1){
- $good_status = 'SELLER_RECEIVED';
- }
- $shop_status = 'WAIT_SELLER_AGREE';
- if($item['is_agree']){
- $shop_status = 'WAIT_BUYER_RETURN_GOODS';
- }
- if($item['is_user_send']){
- $shop_status = 'WAIT_SELLER_CONFIRM_GOODS';
- }
- if($item['status'] == OrderRefund::STATUS_REFUND_AGREE){
- $shop_status = 'SUCCESS';
- }
- if($item['status'] == OrderRefund::STATUS_REFUSE){
- $shop_status = 'SELLER_REFUSE_BUYER';
- }
- if($item['is_user_cancel'] == 1){
- $shop_status = 'CLOSED';
- }
-
- $_data = [
- 'shop_id' => (int)$shop_id,
- 'outer_as_id' => $item['order_refund_no'],
- 'so_id' => $o['order_no'],
- 'type' => '普通退货',
- 'shop_status' => $shop_status,
- 'good_status' => $good_status,
- 'question_type' => '普通退货',
- 'refund' => (float)$o['pay_price'],
- 'payment' => 0.00,
- 'items' => $goodsList,
- ];
- if($item['user_send_express_no']){
- $_data['l_id'] = $item['user_send_express_no'];
- $_data['logistics_company'] = $item['user_send_express'];
- }
- $data[] = $_data;
- $upcount++;
- $upOrderIds[] = $item->id;
- $start_id = $item->id;
- if(count($data) >= $max){
- break;
- }
- }
- $updata = $data;
- if(empty($updata)){
- throw new \Exception('提交数据为空' . json_encode(func_get_args()));
- }
- $response = self::api($store_id, ServeHttp::UPLOAD_AFTERSALE, $updata);
- debug_log(['orderRefund2Jst', $response, $upOrderIds, $updata], __CLASS__ . '.log');
- if($response['code']){
- debug_log(['orderRefund2Jst', $response, $upOrderIds, $updata], __CLASS__ . '.log');
- }
- if(isset($response['data']) && isset($response['data']['datas'])){
- foreach($response['data']['datas'] as $item){
- if(!$item['issuccess']){
- debug_log(['orderRefund2Jst', $item], __CLASS__ . '.log');
- }else{
- // self::lockLocalJstGoodsNum($list[$item['so_id']], 1);
- }
- }
- }
- if($count > 1 && ($count - $upcount > 1)){
- $queue = queue_push(new \app\jobs\jushuitan\OrderRefund2JSTJob([
- 'id' => $store_id,
- 'start_id' => $start_id + 1,
- 'count' => $count - $upcount,
- ]), 1);
- }
- sleep(1);
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function afterGoodsSave($goods) {
- try{
- if(!self::isopen($goods->store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $cacheKey = 'executeGoods2JST' . $goods->id;
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- return;
- }
- $second = 10;
- cache()->set($cacheKey, 1, $second);
- $queue = queue_push(new \app\jobs\jushuitan\Goods2JSTJob([
- 'id' => $goods->store_id,
- 'start_id' => $goods->id,
- ]), $second);
- $queue = queue_push(new \app\jobs\jushuitan\Goods2JSTJob([
- 'id' => $goods->store_id,
- 'start_id' => $goods->id,
- 'upType' => 1,
- ]), $second);
- return $queue;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function afterCatSave($cat) {
- try{
- if(!self::isopen($cat->store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $cacheKey = 'executeCat2JST' . $cat->id;
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- return;
- }
- $second = 10;
- cache()->set($cacheKey, 1, $second);
- $queue = queue_push(new \app\jobs\jushuitan\Cat2JSTJob([
- 'id' => $cat->store_id,
- 'start_id' => $cat->id,
- ]), $second);
- return $queue;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function lockLocalJstGoodsNumList($store_id) {
- $list = [];
- $cacheKeyList = 'lockLocalJstGoodsNumList' . self::$store_type . $store_id;
- $cacheListV = cache()->get($cacheKeyList) ? : [];
- foreach ($cacheListV as $gid) {
- if(self::$store_type == self::STORE_TYPE_STORE){
- $goods = Goods::findOne($gid);
- if(!$goods['jst_goods_id']){
- continue;
- }
- }
- if(self::$store_type == self::STORE_TYPE_SUPPLIER){
- $glist = (new PlatformForm(['id' => $gid]))->goodsInfo();
- if($glist['code'] == 0 && $glist['data']['count'] == 1){
- $goods = $glist['data']['list'][0];
- }
- if(!$goods['jst_goods_id']){
- continue;
- }
- $goods['attr'] = $goods['attrs'];
- }
- $gattr = json_decode($goods['attr'], true);
- foreach($gattr as $gattr_item){
- $gattr_ids = array_column($gattr_item['attr_list'], 'attr_id');
- sort($gattr_ids);
- $cacheKey = 'lockLocalJstGoodsNum' . self::$store_type . $store_id . '_' . $goods['id'] . '_' . implode('_', $gattr_ids);
- $cacheV = cache()->get($cacheKey) ? : 0;
- if($cacheV){
- $list[] = [
- 'attr_ids' => implode(',', $gattr_ids),
- 'no' => $gattr_item['no'],
- 'i_ids' => self::$store_type == self::STORE_TYPE_STORE ? self::skuid2Jst($goods['store_id'], $goods, $gattr_item) : $gattr_item['no'],
- 'cacheV' => $cacheV,
- ];
- }
- }
- }
- debug_log([__FUNCTION__, $list], __CLASS__ . '.log');
- return [
- 'code' => 0,
- 'data' => $list,
- ];
- }
-
- public static function lockLocalJstGoodsNumGet($store_id, $goods, $gattr_item) {
- $gattr_ids = array_column($gattr_item['attr_list'], 'attr_id');
- sort($gattr_ids);
- $cacheKey = 'lockLocalJstGoodsNum' . self::$store_type . $store_id . '_' . $goods['id'] . '_' . implode('_', $gattr_ids);
- $cacheV = cache()->get($cacheKey);
- return $cacheV > 0 ? $cacheV : 0;
- }
-
- public static function lockLocalJstGoodsNum($order, $unlock = 0, $changedAttributes = []) {
- try{
- $store_id = $order->store_id;
- debug_log([__FUNCTION__, $order->id, '锁库存逻辑', $unlock, $changedAttributes, self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- $order->refresh();
- $od = $order->detail;
- if(!$od){
- debug_log([__FUNCTION__, $order->id, '订单商品还没录入,跳出'], __CLASS__ . '.log');
- return;
- }
- // \Yii::error($od);
- $cacheKeyList = 'lockLocalJstGoodsNumList' . self::$store_type . $store_id;
- $cacheListV = cache()->get($cacheKeyList) ? : [];
- $cacheKeyOrder = 'lockLocalJstGoodsNumOrder' . self::$store_type . $store_id . '_' . $order->id;
- $cacheOrderV = cache()->get($cacheKeyOrder);
- $cacheTtl = 60 * 25;
- if($unlock){
- if(empty($cacheOrderV)){
- debug_log([__FUNCTION__, $order->id, $cacheKeyOrder, $cacheOrderV, '缓存不存在,无需解锁'], __CLASS__ . '.log');
- return;
- }else{
- cache()->delete($cacheKeyOrder);
- }
- }else{
- if($cacheOrderV){
- debug_log([__FUNCTION__, $order->id, $cacheOrderV, '缓存已存在,无需加锁'], __CLASS__ . '.log');
- return;
- }else{
- if($changedAttributes){
- debug_log([__FUNCTION__, $order->id, $changedAttributes, '订单创建时缓存未初始化,无需操作'], __CLASS__ . '.log');
- return;
- }
- debug_log([__FUNCTION__, $cacheKeyOrder, '锁关联订单', self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- cache()->set($cacheKeyOrder, 1, $cacheTtl);
- }
- }
- foreach($od as $item){
- $goods = json_decode($item['goods_info'], true);
- if(!$goods['jst_goods_id']){
- continue;
- }
- $attr = json_decode($item['attr'], true);
- $attr_ids = array_column($attr, 'attr_id');
- sort($attr_ids);
- $gattr = json_decode($goods['attr'], true);
- foreach($gattr as $gattr_item){
- $gattr_ids = array_column($gattr_item['attr_list'], 'attr_id');
- sort($gattr_ids);
- if(implode('_', $attr_ids) == implode('_', $gattr_ids)){
- $cacheKey = 'lockLocalJstGoodsNum' . self::$store_type . $store_id . '_' . $goods['id'] . '_' . implode('_', $attr_ids);
- $cacheV = cache()->get($cacheKey) ? : 0;
- if($unlock){
- if(empty($cacheV)){
- debug_log([__FUNCTION__, $order->id, $cacheV, '缓存不存在,无需解锁'], __CLASS__ . '.log');
- return;
- }else{
- $val = $cacheV - $item['num'];
- cache()->set($cacheKey, $val, $cacheTtl);
- if($val <= 0){
- cache()->set($cacheKeyList, array_unique(array_diff($cacheListV, [$goods['id']])), $cacheTtl);
- }
- }
- }else{
- cache()->set($cacheKey, $cacheV + $item['num'], $cacheTtl);
- cache()->set($cacheKeyList, array_unique(array_merge($cacheListV, [$goods['id']])), $cacheTtl);
- }
- debug_log([__FUNCTION__, $cacheKey, cache()->get($cacheKey), $cacheKeyList, cache()->get($cacheKeyList),self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- break;
- }
- }
- }
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function afterOrderSave($order, $changedAttributes = []) {
- try{
- if(!self::isopen($order->store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- self::lockLocalJstGoodsNum($order, 0, $changedAttributes);
- $is_cod = $order['pay_type'] == Order::PAY_TYPE_COD;
- $shop_status = self::orderStatusKey2Jst($order['trade_status']);
- if(!$shop_status && !$is_cod){
- return [
- 'code' => 1,
- 'msg' => '不需要上传',
- ];
- }
- if(!self::isopen($order->store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- $cacheKey = 'executeOrder2JST' . $order->id;
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- return;
- }
- $second = 10;
- cache()->set($cacheKey, 1, $second);
- $queue = queue_push(new \app\jobs\jushuitan\Order2JSTJob([
- 'id' => $order->store_id,
- 'start_id' => $order->id,
- ]), $second);
- return $queue;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function afterOrderRefundSave($insert, $changedAttributes, $orderRefund) {
- try{
- if(!self::isopen($orderRefund->store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能');
- }
- // if(!$insert){
- // return [
- // 'code' => 1,
- // 'msg' => '不需要上传',
- // ];
- // }
- $cacheKey = 'executeOrderRefund2JST' . $orderRefund->id;
- $cacheV = cache()->get($cacheKey);
- if($cacheV){
- return;
- }
- $second = 2;
- cache()->set($cacheKey, 1, $second);
- $queue = queue_push(new \app\jobs\jushuitan\OrderRefund2JSTJob([
- 'id' => $orderRefund->store_id,
- 'start_id' => $orderRefund->id,
- ]), $second);
- return $queue;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function lockLocalJstGoodsNumSupplier($order, $unlock = 0, $changedAttributes = []) {
- try{
- $supplier = Supplier::findOne(['cloud_supplier_id' => $order->supplier_id]);
- $store_id = $supplier->id;
- if(!self::isopen($store_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能' . json_encode(func_get_args()));
- }
- debug_log([__FUNCTION__, $order->id, '锁库存逻辑', $unlock, $changedAttributes, self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- try{
- //批发单刷新
- if($order instanceof \yii\base\Model){
- $order->refresh();
- }
- } catch (\Exception $ex) {
- }
- $od = $order->detail;
- if(!$od){
- debug_log([__FUNCTION__, $order->id, '订单商品还没录入,跳出'], __CLASS__ . '.log');
- return;
- }
- // \Yii::error($od);
- $cacheKeyList = 'lockLocalJstGoodsNumList' . self::$store_type . $store_id;
- $cacheListV = cache()->get($cacheKeyList) ? : [];
- $cacheKeyOrder = 'lockLocalJstGoodsNumOrder' . self::$store_type . $store_id . '_' . $order->id;
- $cacheOrderV = cache()->get($cacheKeyOrder);
- $cacheTtl = 60 * 25;
- if($unlock){
- if(empty($cacheOrderV)){
- debug_log([__FUNCTION__, $order->id, $cacheKeyOrder, $cacheOrderV, '缓存不存在,无需解锁'], __CLASS__ . '.log');
- return;
- }else{
- cache()->delete($cacheKeyOrder);
- }
- }else{
- if($cacheOrderV){
- debug_log([__FUNCTION__, $order->id, $cacheOrderV, '缓存已存在,无需加锁'], __CLASS__ . '.log');
- return;
- }else{
- if($changedAttributes){
- debug_log([__FUNCTION__, $order->id, $changedAttributes, '订单创建时缓存未初始化,无需操作'], __CLASS__ . '.log');
- return;
- }
- debug_log([__FUNCTION__, $cacheKeyOrder, '锁关联订单', self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- cache()->set($cacheKeyOrder, 1, $cacheTtl);
- }
- }
- foreach($od as $item){
- $glist = (new PlatformForm(['id' => $item['goods_id']]))->goodsInfo();
- if($glist['code'] == 0 && $glist['data']['count'] == 1){
- $goods = $glist['data']['list'][0];
- }
- if(!$goods['jst_goods_id']){
- continue;
- }
- //兼容批发、转单数据
- $attr = is_array($item['attr']) ? $item['attr'] : json_decode($item['attr'], true);
- $attr_ids = array_column($attr['attr_list'] ?? $attr, 'attr_id');
- sort($attr_ids);
- $gattr = json_decode($goods['attrs'], true);
- foreach($gattr as $gattr_item){
- $gattr_ids = array_column($gattr_item['attr_list'], 'attr_id');
- sort($gattr_ids);
- if(implode('_', $attr_ids) == implode('_', $gattr_ids)){
- $cacheKey = 'lockLocalJstGoodsNum' . self::$store_type . $store_id . '_' . $goods['id'] . '_' . implode('_', $attr_ids);
- $cacheV = cache()->get($cacheKey) ? : 0;
- if($unlock){
- if(empty($cacheV)){
- debug_log([__FUNCTION__, $order->id, $cacheV, '缓存不存在,无需解锁'], __CLASS__ . '.log');
- return;
- }else{
- $val = $cacheV - $item['num'];
- cache()->set($cacheKey, $val, $cacheTtl);
- if($val <= 0){
- cache()->set($cacheKeyList, array_unique(array_diff($cacheListV, [$goods['id']])), $cacheTtl);
- }
- }
- }else{
- cache()->set($cacheKey, $cacheV + $item['num'], $cacheTtl);
- cache()->set($cacheKeyList, array_unique(array_merge($cacheListV, [$goods['id']])), $cacheTtl);
- }
- debug_log([__FUNCTION__, $cacheKey, cache()->get($cacheKey), $cacheKeyList, cache()->get($cacheKeyList),self::lockLocalJstGoodsNumList($store_id)], __CLASS__ . '.log');
- break;
- }
- }
- }
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function afterPurchaseOrderSave($order, $insert = false, $changedAttributes = []) {
- try{
- if(!$insert){
- return;
- }
- self::initStoreType(self::STORE_TYPE_SUPPLIER);
- self::lockLocalJstGoodsNumSupplier($order, 0, $changedAttributes);
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function cloudTransitOrder($order_no = 'PO123123') {
- $order = null;
- try{
- $orderTransit = \app\models\OrderTransit::findOne(['cloud_order_no' => $order_no]);
- $orderList = (new SupplierForm(['order_id' => (string)$orderTransit['cloud_order_id']]))->supplierPurchaseOrderList($orderTransit['cloud_supplier_id'], 1);
- if($orderList['code'] == 0 && $orderList['data']['count']){
- $order = $orderList['data']['list'][0];
- $goods_list = $order['goods_list'];
- $order = json_decode(json_encode($order));
- $order->detail = $goods_list;
- $order->id = $order->order_no;
- }
- } catch (\Exception $ex) {
- \Yii::error($ex);
- }
- return $order;
- }
-
- public static function afterTransitOrderSave($orderTransit, $insert = false, $changedAttributes = []) {
- try{
- if(!$insert){
- return;
- }
- self::initStoreType(self::STORE_TYPE_SUPPLIER);
- $cloudOrder = self::cloudTransitOrder($orderTransit['cloud_order_no']);
- self::lockLocalJstGoodsNumSupplier($cloudOrder);
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function supplierOrder2Jst($supplier_id = 0, $start_time = 0) {
- try{
- self::initStoreType(self::STORE_TYPE_SUPPLIER);
- if(!self::isopen($supplier_id)){
- return [
- 'code' => 1,
- 'msg' => '未配置此功能',
- ];
- // throw new \Exception('未配置此功能' . json_encode(func_get_args()));
- }
- $shop_id = self::getConf($supplier_id, 'shop_id');
- if(empty($shop_id)){
- return [
- 'code' => 1,
- 'msg' => 'shop_id不存在,不能同步订单',
- ];
- // throw new \Exception('shop_id不存在,不能同步订单' . json_encode(func_get_args()));
- }
-
- if($start_time == 0){
- $upload_order_time_last = self::getConf($supplier_id, 'upload_order_time_last');
- if($upload_order_time_last){
- $start_time = $upload_order_time_last;
- }else{
- $start_time = time() - 600;
- }
- }
-
- $form = new SupplierForm();
- $supplierOrder = $form->supplierOrderList2Jst($supplier_id, $start_time);
- if($supplierOrder['code']){
- throw new \Exception('获取订单失败,' . $supplierOrder['msg'] . json_encode(func_get_args()));
- }
- if(empty($supplierOrder['data']['list'])){
- return [
- 'code' => 0,
- 'msg' => '订单数据为空',
- ];
- }
- $max = 50;
- $arr = array_chunk($supplierOrder['data']['list'], $max);
- foreach($arr as $list){
- $list = array_combine(array_column($list, 'so_id'), $list);
- $data = [];
- $upOrderIds = [];
- foreach($list as $_data){
- $up = 1;
- $_data['labels'] = 'cyy,' . $_data['labels'];
- $_data['shop_id'] = (int)$shop_id;
- $_data['is_cod'] = (bool)$_data['is_cod'];
- $_data['pay_amount'] = (float)$_data['pay_amount'];
- $_data['freight'] = (float)$_data['freight'];
- $_data['pay']['amount'] = (float)$_data['pay']['amount'];
- foreach($_data['items'] as &$item){
- if(empty($item['sku_id'])){
- $up = 0;
- debug_log(['supplierOrder2Jst', 'sku_id为空', $_data['so_id']], __CLASS__ . '.log');
- break;
- }
- $item['outer_oi_id'] = md5($item['outer_oi_id']);
- $item['qty'] = (int)$item['qty'];
- $item['amount'] = (float)$item['amount'];
- $item['base_price'] = (float)$item['base_price'];
- }
- if(!$up){
- continue;
- }
- $data[] = $_data;
- $upOrderIds[] = $_data['so_id'];
- }
- $updata = $data;
- if(empty($updata)){
- return [
- 'code' => 0,
- 'msg' => '提交数据为空',
- ];
- throw new \Exception('提交数据为空' . json_encode(func_get_args()));
- }
- self::saveConf($supplier_id, ['upload_order_time_last' => time()]);
- $response = self::api($supplier_id, ServeHttp::UPLOAD_ORDERS, $updata);
- debug_log(['supplierOrder2Jst', $response, $upOrderIds, $updata], __CLASS__ . '.log');
- if($response['code']){
- debug_log(['supplierOrder2Jst', $response, $upOrderIds, $updata], __CLASS__ . '.log');
- }
- if(isset($response['data']) && isset($response['data']['datas'])){
- foreach($response['data']['datas'] as $item){
- if(!$item['issuccess']){
- debug_log(['supplierOrder2Jst', $item], __CLASS__ . '.log');
- }else{
- //批发
- $order2 = \app\models\PurchaseOrder::findOne(['cloud_order_no' => $item['so_id']]);
- if($order2){
- $order = \app\models\PurchaseOrder::findOne(['order_no' => $order2['order_no']]);
- }
- if(!$order){
- //转单
- $order = self::cloudTransitOrder($item['so_id']);
- }
- self::lockLocalJstGoodsNumSupplier($order, 1);
- }
- }
- }
- // sleep(1);
- }
- return $response;
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
-
- public static function checkGoodsImport2Store($store_id, $params) {
- try {
- $id = $params['i_id'];
- $goods = Goods::find()->where(['jst_goods_id' => trim($id), 'store_id' => $store_id, 'is_delete' => 0])->select(['id'])->limit(1)->one();
- return [
- 'code' => 0,
- 'data' => $goods,
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- // 添加店铺商品
- public static function jstGoods2Store($store_id, $params)
- {
- $goods = self::queryJstGoods($store_id, $params['i_id']);
- if ($goods['code'] != 0) {
- return $goods;
- }
- $goods = $goods['data'];
- $store_goods = Goods::find()->where(['jst_goods_id' => trim($goods['i_id']), 'store_id' => $store_id, 'is_delete' => 0])->select(['id'])->limit(1)->one();
- $model = new GoodsForm(['id' => $store_goods['id']]);
- $model->jst_goods_id = $goods['i_id'];
- $model->status = 1;
- $model->store_id = $store_id;
- $model->name = $params['name'];
- $model->price = $params['price'];
- $model->cost_price = $params['cost_price'];
- $model->original_price = $params['original_price'];
- $model->goods_num = $goods['qty'];
- $model->goods_no = $goods['i_id'];
- $model->use_attr = 1;
- $attr = $params['attr'];
- foreach($attr as &$item){
- foreach($goods['skus'] as $sku){
- if($sku['sku_id'] == $item['no']){
- $item['num'] = $sku['qty'];
- }
- }
- }
- $model->attr = $attr;
- $model->cat_id = $params['cat'];
- $model->service = '';
- $model->content = '';
- $model->product_type = 0;
- $model->form = ['is_form' => 0];
- $model->cover_pic = $goods['pic'];
- $pics = [];
- foreach($goods['pics'] as $pic){
- $pics[] = ['pic_url' => $pic];
- }
- $model->goods_pic_list = $pics;
- $res = $model->save();
- if($res['code'] != 0){
- \Yii::error([__FUNCTION__, $res, $goods, $params, $model]);
- return $res;
- }
- return $res;
- }
- // 批量添加店铺商品
- public static function jstGoods2StoreBatch($store_id, $params)
- {
- try{
- $i_ids = explode(',', $params['i_ids']);
- foreach($i_ids as $i_id){
- $goods = self::queryJstGoods($store_id, $i_id);
- if ($goods['code'] != 0) {
- return $goods;
- }
- $goods = $goods['data'];
- $attr = $goods['_attr'];
- $store_goods = Goods::find()->where(['jst_goods_id' => trim($goods['i_id']), 'store_id' => $store_id, 'is_delete' => 0])->select(['id'])->limit(1)->one();
- $model = new GoodsForm(['id' => $store_goods['id']]);
- $model->jst_goods_id = $goods['i_id'];
- $model->status = 1;
- $model->store_id = $store_id;
- $model->name = $goods['name'];
- $model->price = $goods['market_price'] ?: 0;
- $model->cost_price = $goods['s_price'] ?: 0;
- $model->original_price = $goods['market_price'] ?: 0;
- $model->goods_num = $goods['qty'];
- $model->goods_no = $goods['i_id'];
- $model->use_attr = 1;
- $model->attr = $attr;
- $model->cat_id = $params['cat'];
- $model->service = '';
- $model->content = '';
- $model->product_type = 0;
- $model->form = ['is_form' => 0];
- $model->cover_pic = $goods['pic'];
- $pics = [];
- foreach($goods['pics'] as $pic){
- $pics[] = ['pic_url' => $pic];
- }
- $model->goods_pic_list = $pics;
- $res = $model->save();
- if($res['code'] != 0){
- \Yii::error([__FUNCTION__, $res, $goods, $params, $model]);
- return $res;
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage() . $e->getLine()
- ];
- }
- }
- public static function commonHandleStore($supplier_id, $data, $id = 0) {
- $supplier = Supplier::findOne(['id' => $supplier_id, 'is_delete' => 0]);
- if (!$supplier) {
- return [
- 'code' => 1,
- 'msg' => '供货商未找到',
- ];
- }
- $supplierForm = new SupplierForm();
- $supplierForm->attributes = $data;
- $supplierForm->token_supplier_id = $supplier->cloud_supplier_id;
- $setGoods = $supplierForm->setGoods();
- if ($setGoods['code'] == 1) {
- return $setGoods;
- }
- // 提交审核
- $supplierForm = new SupplierForm();
- $supplierForm->attributes = ['goods_id' => $setGoods['data']['goods_id']];
- $supplierForm->token_supplier_id = $supplier->cloud_supplier_id;
- $submitAudit = $supplierForm->auditSubmit();
- if ($submitAudit['code'] == 1) {
- return $submitAudit;
- }
- // 审核商品
- $form = new PlatformForm();
- $form->attributes = [
- 'id' => $submitAudit['data']['goods_id'],
- 'status' => 1,
- ];
- return $form->auditHandle();
- }
- //attr参数包含店铺和供应商所需参数
- public static function handleAttr(&$goods) {
- $_attr = [];
- $skus = $goods['skus'];
- $image = $goods['pic'];
- foreach ($goods['skus'] as &$sku) {
- $attr_list = [
- [
- 'attr_group_name' => '规格',
- 'attr_name' => $sku['properties_value']
- ]
- ];
- $attr = [
- 'attr_list' => $attr_list,
- 'num' => $sku['qty'],
- 'price' => sprintf('%.2f', $sku['market_price']),
- 'cost_price' => sprintf('%.2f', $sku['sale_price']),
- 'no' => $sku['sku_id'],
- 'pic' => $sku['pic'] == '' ? $image : $sku['pic'],
- 'share_commission_first' => '',
- 'share_commission_second' => '',
- 'share_commission_third' => '',
- 'wholesale_price' => sprintf('%.2f', $sku['sale_price']),
- 'original_price' => sprintf('%.2f', $sku['market_price']),
- ];
- if(self::$store_type == self::STORE_TYPE_SUPPLIER){
- $attr['price'] = sprintf('%.2f', $sku['sale_price']);
- }
- $_attr[] = $attr;
- $sku['_attr'] = $attr;
- }
- return $_attr;
- }
-
- public static function checkGoodsImport2Supplier($params) {
- try {
- $id = $params['i_id'];
- $cloud_store_token = get_platform_token();
- $goods_url = "/cloud/user/getJstGoods";
- $goods_data = [];
- $goods_data['access_token'] = $cloud_store_token; //获取供货商的token信息
- $goods_data['jst_goods_id'] = $id; //默认为 1
- $domain = (new OptionSetting)->getCloudDomainName();
- $goods_data_info = cloud_post($domain . $goods_url,$goods_data);
- $goods_data_info = json_decode($goods_data_info,true);
- if($goods_data_info['code'] != 0){
- throw new \Exception($goods_data_info['msg']);
- }else{
- return $goods_data_info;
- }
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage()
- ];
- }
- }
- // 添加云仓商品
- public static function jstGoods2Supplier($supplier_id, $params)
- {
- $goods = self::queryJstGoods($supplier_id, $params['i_id']);
- if ($goods['code'] != 0) {
- return $goods;
- }
- $goods = $goods['data'];
- $attr = $params['attr'];
- foreach($attr as &$item){
- foreach($goods['skus'] as $sku){
- if($sku['sku_id'] == $item['no']){
- $item['num'] = $sku['qty'];
- }
- }
- }
- $data = [
- 'cat_id' => \implode(',', $params['cat']),
- 'name' => $params['name'],
- 'goods_no' => (string)$params['i_id'],
- 'g_s_pic_url' => $goods['pic'],
- 'desc' => $params['name'],
- 'g_price' => $params['price'],
- 'g_wholesale_price' => $params['wholesale_price'],
- 'g_wholesale_ladder_rebate' => '[]',
- 'g_wholesale_rebate_switch' => '0',
- 'weight' => '',
- 'g_original_price' => $params['original_price'],
- 'g_unit' => $goods['unit'],
- 'g_shop_count' => 1,
- 'num' => $goods['qty'],
- 'use_attr' => '1',
- 'g_pic_list' => $goods['pics'],
- 'g_send_type' => '0',
- 'attrs' => $attr,
- 'is_change' => 1,
- 'jst_goods_id' => $params['i_id'],
- 'market_price' => sprintf('%.2f', $goods['market_price']),
- ];
- return self::commonHandleSupplier($supplier_id, $data, $params['i_id']);
- }
- // 批量添加云仓商品
- public static function jstGoods2SupplierBatch($supplier_id, $params)
- {
- try{
- $i_ids = explode(',', $params['i_ids']);
- foreach($i_ids as $i_id){
- $goods = self::queryJstGoods($supplier_id, $i_id);
- if ($goods['code'] != 0) {
- return $goods;
- }
- $goods = $goods['data'];
- $attr = $goods['_attr'];
- $data = [
- 'cat_id' => \implode(',', $params['cat']),
- 'name' => $goods['name'],
- 'goods_no' => (string)$i_id,
- 'g_s_pic_url' => $goods['pic'],
- 'desc' => $goods['name'],
- 'g_price' => sprintf('%.2f', $goods['s_price']),
- 'g_wholesale_price' => sprintf('%.2f', $goods['s_price']),
- 'g_wholesale_ladder_rebate' => '[]',
- 'g_wholesale_rebate_switch' => '0',
- 'weight' => '',
- 'g_original_price' => sprintf('%.2f', $goods['s_price']),
- 'g_unit' => $goods['unit'],
- 'g_shop_count' => 1,
- 'num' => $goods['qty'],
- 'use_attr' => '1',
- 'g_pic_list' => $goods['pics'],
- 'g_send_type' => '0',
- 'attrs' => $attr,
- 'is_change' => 1,
- 'jst_goods_id' => $i_id,
- 'market_price' => sprintf('%.2f', $goods['market_price']),
- ];
- $result = self::commonHandleSupplier($supplier_id, $data, $i_id);
- if (intval($result['code']) !== 0) {
- throw new \Exception($result['msg']);
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage() . $e->getLine()
- ];
- }
- }
- // 添加店铺商品
- public static function jstSupplierGoods2Store($store_id, $params)
- {
- $goods = self::queryJstSupplierGoods($store_id, $params['i_id']);
- if ($goods['code'] != 0) {
- return $goods;
- }
- $goods = $goods['data'];
- $store_goods = Goods::find()->where(['jst_goods_id' => trim($goods['style_code']), 'store_id' => $store_id, 'is_delete' => 0])->select(['id'])->limit(1)->one();
- $model = new GoodsForm(['id' => $store_goods['id']]);
- $model->jst_goods_id = $goods['style_code'];
- $model->jst_supplier_id = $goods['_supplier_co_id'] ?: 0;
- $model->status = 1;
- $model->store_id = $store_id;
- $model->name = $params['name'];
- $model->price = $params['price'];
- $model->cost_price = $params['cost_price'];
- $model->original_price = $params['original_price'];
- $model->goods_num = $goods['qty'];
- $model->goods_no = $goods['style_code'];
- $model->use_attr = 1;
- $attr = $params['attr'];
- // foreach($attr as &$item){
- // foreach($goods['skus'] as $sku){
- // if($sku['sku_id'] == $item['no']){
- // $item['num'] = $sku['qty'];
- // }
- // }
- // }
- $model->attr = $attr;
- $model->cat_id = $params['cat'];
- $model->service = '';
- $model->content = '';
- $model->product_type = 0;
- $model->form = ['is_form' => 0];
- $model->cover_pic = $goods['main_image_list'][0] ?? '';
- $pics = [];
- foreach($goods['main_image_list'] as $pic){
- $pics[] = ['pic_url' => $pic];
- }
- $model->goods_pic_list = $pics;
- $model->content = $goods['_desc'];
-
- if($goods['__goods_info'] && $goods['__goods_info']['data']){
- $model->video_url = $goods['__goods_info']['data']['item_photo']['item_video'] ?: $goods['__goods_info']['data']['item_photo']['goods_video'];
- }
-
- $res = $model->save();
- if($res['code'] != 0){
- \Yii::error([__FUNCTION__, $res, $goods, $params, $model]);
- return $res;
- }
- return $res;
- }
- // 批量添加店铺商品
- public static function jstSupplierGoods2StoreBatch($store_id, $params)
- {
- try{
- $i_ids = explode(',', $params['i_ids']);
- foreach($i_ids as $i_id){
-
- $goods = self::queryJstSupplierGoods($store_id, $i_id);
- if ($goods['code'] != 0) {
- return $goods;
- }
- $goods = $goods['data'];
- $attr = $goods['_attr'];
-
- $store_goods = Goods::find()->where(['jst_goods_id' => trim($goods['style_code']), 'store_id' => $store_id, 'is_delete' => 0])->select(['id'])->limit(1)->one();
- $model = new GoodsForm(['id' => $store_goods['id']]);
- $model->jst_goods_id = $goods['style_code'];
- $model->jst_supplier_id = $goods['_supplier_co_id'] ?: 0;
- $model->status = 1;
- $model->store_id = $store_id;
- $model->name = $goods['item_name'];
- $model->price = $goods['min_sale_price'];
- $model->cost_price = $goods['min_supply_price'];
- $model->original_price = $goods['min_sale_price'];
- $model->goods_num = $goods['qty'];
- $model->goods_no = $goods['style_code'];
- $model->use_attr = 1;
- // $attr = $params['attr'];
- // foreach($attr as &$item){
- // foreach($goods['skus'] as $sku){
- // if($sku['sku_id'] == $item['no']){
- // $item['num'] = $sku['qty'];
- // }
- // }
- // }
- $model->attr = $attr;
- $model->cat_id = $params['cat'];
- $model->service = '';
- $model->content = '';
- $model->product_type = 0;
- $model->form = ['is_form' => 0];
- $model->cover_pic = $goods['main_image_list'][0] ?? '';
- $pics = [];
- foreach($goods['main_image_list'] as $pic){
- $pics[] = ['pic_url' => $pic];
- }
- $model->goods_pic_list = $pics;
- $model->content = $goods['_desc'];
- if($goods['__goods_info'] && $goods['__goods_info']['data']){
- $model->video_url = $goods['__goods_info']['data']['item_photo']['item_video'] ?: $goods['__goods_info']['data']['item_photo']['goods_video'];
- }
- $res = $model->save();
- if($res['code'] != 0){
- \Yii::error([__FUNCTION__, $res, $goods, $params, $model]);
- return $res;
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功'
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage() . $e->getLine()
- ];
- }
- }
- // 添加云仓商品
- public static function jstSupplierGoods2Supplier($supplier_id, $params)
- {
- $supplierGoods = self::queryJstSupplierGoods($supplier_id, $params['i_id']);
- if($supplierGoods['code']){
- return $supplierGoods;
- }
-
- $attr = $params['attr'];
-
- $data = [
- 'cat_id' => \implode(',', $params['cat']),
- 'name' => $params['name'],
- 'goods_no' => (string)$params['i_id'],
- 'g_s_pic_url' => $supplierGoods['data']['main_image_list'][0] ?? '',
- 'desc' => $supplierGoods['data']['_desc'],
- 'g_price' => $params['price'],
- 'g_wholesale_price' => $params['wholesale_price'],
- 'g_wholesale_ladder_rebate' => '[]',
- 'g_wholesale_rebate_switch' => '0',
- 'weight' => '',
- 'g_original_price' => $params['original_price'],
- 'g_unit' => '',
- 'g_shop_count' => 1,
- 'num' => $supplierGoods['data']['qty'],
- 'use_attr' => '1',
- 'g_pic_list' => $supplierGoods['data']['main_image_list'] ?: [],
- 'g_send_type' => '0',
- 'attrs' => $attr,
- 'is_change' => 1,
- 'jst_goods_id' => $params['i_id'],
- 'jst_supplier_id' => $supplierGoods['data']['_supplier_co_id'] ?: 0,
- 'market_price' => sprintf('%.2f', $supplierGoods['data']['min_sale_price']),
- ];
-
- if($supplierGoods['data']['__goods_info'] && $supplierGoods['data']['__goods_info']['data']){
- $data['video_url'] = $supplierGoods['data']['__goods_info']['data']['item_photo']['item_video'] ?: $supplierGoods['data']['__goods_info']['data']['item_photo']['goods_video'];
- }
-
- return self::commonHandleSupplier($supplier_id, $data, $params['i_id']);
- }
- // 批量添加云仓商品
- public static function jstSupplierGoods2SupplierBatch($supplier_id, $params)
- {
- try{
- $i_ids = explode(',', $params['i_ids']);
- $res = [];
- foreach($i_ids as $i_id){
- $supplierGoods = self::queryJstSupplierGoods($supplier_id, $i_id);
- if($supplierGoods['code']){
- return $supplierGoods;
- }
-
- $attr = $supplierGoods['data']['_attr'];
- $data = [
- 'cat_id' => \implode(',', $params['cat']),
- 'name' => $supplierGoods['data']['item_name'],
- 'goods_no' => (string)$i_id,
- 'g_s_pic_url' => $supplierGoods['data']['main_image_list'][0] ?? '',
- 'desc' => $supplierGoods['data']['_desc'],
- 'g_price' => sprintf('%.2f', $supplierGoods['data']['min_supply_price']),
- 'g_wholesale_price' => sprintf('%.2f', $supplierGoods['data']['min_supply_price']),
- 'g_wholesale_ladder_rebate' => '[]',
- 'g_wholesale_rebate_switch' => '0',
- 'weight' => '',
- 'g_original_price' => sprintf('%.2f', $supplierGoods['data']['min_sale_price']),
- 'g_unit' => '',
- 'g_shop_count' => 1,
- 'num' => $supplierGoods['data']['qty'],
- 'use_attr' => '1',
- 'g_pic_list' => $supplierGoods['data']['main_image_list'] ?: [],
- 'g_send_type' => '0',
- 'attrs' => $attr,
- 'is_change' => 1,
- 'jst_goods_id' => $i_id,
- 'jst_supplier_id' => $supplierGoods['data']['_supplier_co_id'] ?: 0,
- 'market_price' => sprintf('%.2f', $supplierGoods['data']['min_sale_price']),
- ];
-
- if($supplierGoods['data']['__goods_info'] && $supplierGoods['data']['__goods_info']['data']){
- $data['video_url'] = $supplierGoods['data']['__goods_info']['data']['item_photo']['item_video'] ?: $supplierGoods['data']['__goods_info']['data']['item_photo']['goods_video'];
- }
- $result = self::commonHandleSupplier($supplier_id, $data, $i_id);
- $res[] = $result;
- if (intval($result['code']) !== 0) {
- throw new \Exception($result['msg']);
- }
- }
- return [
- 'code' => 0,
- 'msg' => '操作成功',
- 'ress' => $res,
- ];
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'ress' => $res,
- 'msg' => $e->getMessage() . $e->getLine()
- ];
- }
- }
- public static function commonHandleSupplier($supplier_id, $data, $id = 0) {
- $supplier = Supplier::findOne(['id' => $supplier_id, 'is_delete' => 0]);
- if (!$supplier) {
- return [
- 'code' => 1,
- 'msg' => '供货商未找到',
- ];
- }
-
- $_res = ['query' => $data];
- $supplierForm = new SupplierForm();
- $supplierForm->attributes = $data;
- $supplierForm->token_supplier_id = $supplier->cloud_supplier_id;
- $setGoods = $supplierForm->setGoods();
- if ($setGoods['code'] == 1) {
- return array_merge($setGoods, $_res);
- }
- // 提交审核
- $supplierForm = new SupplierForm();
- $supplierForm->attributes = ['goods_id' => $setGoods['data']['goods_id']];
- $supplierForm->token_supplier_id = $supplier->cloud_supplier_id;
- $submitAudit = $supplierForm->auditSubmit();
- if ($submitAudit['code'] == 1) {
- return array_merge($submitAudit, $_res);
- }
- // 审核商品
- $form = new PlatformForm();
- $form->attributes = [
- 'id' => $submitAudit['data']['goods_id'],
- 'status' => 1,
- ];
- return array_merge($form->auditHandle(), $_res);
- }
- //attr参数包含店铺和供应商所需参数
- public static function supplierGoodsHandleAttr(&$supplierGoods) {
- $_attr = [];
- $image = $supplierGoods['main_image_list'][0];
- $qty = $supplierGoods['__qty'];
- $ginfo = $supplierGoods['__goods_info']['data'];
-
- $desc = $ginfo['describe'] ?? '';
- $imgs = $ginfo['item_photo']['item_detail_images'];
- if($imgs){
- $desc .= '<br><img src="' . implode('"/><img src="', $imgs) . '"/>';
- }
- $supplierGoods['_desc'] = $desc;
-
- foreach ($supplierGoods['__goods_info']['data']['item_sku_list'] as &$sku) {
- $attr_list = [
- [
- 'attr_group_name' => $ginfo['first_spec_name'],
- 'attr_name' => $sku['first_spec_value_name'],
- ],
- ];
- if($ginfo['second_spec_name']){
- $attr_list[] = [
- 'attr_group_name' => $ginfo['second_spec_name'],
- 'attr_name' => $sku['second_spec_value_name'],
- ];
- }
-
- $num = 0;
- if($qty['data']['list']){
- foreach($qty['data']['list'] as $iqty){
- if($iqty['item_code'] == $sku['item_code']){
- $num = $iqty['stock'];
- break;
- }
- }
- }
- if($qty['data']['inventorys']){
- foreach($qty['data']['inventorys'] as $iqty){
- if($iqty['sku_id'] == $sku['item_code']){
- $num = $iqty['qty'];
- break;
- }
- }
- }
- // $attr_list = [
- // [
- // 'attr_group_name' => '规格',
- // 'attr_name' => $sku['properties_value']
- // ]
- // ];
- $attr = [
- 'attr_list' => $attr_list,
- 'num' => $num,
- 'price' => sprintf('%.2f', $sku['sale_price']),
- 'cost_price' => sprintf('%.2f', $sku['supply_price']),
- 'wholesale_price' => sprintf('%.2f', $sku['supply_price']),
- 'original_price' => sprintf('%.2f', $sku['sale_price']),
- 'no' => $sku['item_code'],
- 'weight' => $sku['weight'],
- 'pic' => $sku['pic'] == '' ? $image : $sku['pic'],
- 'share_commission_first' => '',
- 'share_commission_second' => '',
- 'share_commission_third' => '',
- ];
- if(self::$store_type == self::STORE_TYPE_SUPPLIER){
- $attr['price'] = sprintf('%.2f', $sku['supply_price']);
- }
- $sku['qty'] = $attr['num'];
- $sku['_attr'] = $attr;
- $_attr[] = $attr;
- }
- return $_attr;
- }
- }
|