jh-admin/addon/supply/model/goods/GoodsWarehousing.php

552 lines
24 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace addon\supply\model\goods;
use addon\supply\model\CloudApi;
use app\model\BaseModel;
use app\model\goods\Goods as GoodsModel;
use app\model\system\Cron;
use app\model\upload\Album;
class GoodsWarehousing extends BaseModel
{
private $supply_site_id;
private $SupplyInfo;
protected $site_id = 0;
protected $goods_spec_format = '';// 商品多规格 必须,否则多规格无效
public function __construct($SupplyInfo = [])
{
$this->supply_site_id = $SupplyInfo['supplier_site_id'] ?? 0;
$this->SupplyInfo = $SupplyInfo;
}
public function getInfo($condition = [], $field = '*')
{
$result = model('supply_goods_warehousing')->getInfo($condition, $field);
return $result;
}
public function getPageList($condition, $field = '*', $order = '', $page, $page_size)
{
$list = model('supply_goods_warehousing')->pageList($condition, $field, $order, $page, $page_size);
return $list;
}
/***
* 添加关注
* @param $data
* @return int|string
*/
public function addGoodsWarehousing($data)
{
$result = model('supply_goods_warehousing')->add($data);
return $result;
}
/***
* 删除关注
* @param $condition
* @return int
*/
public function deleteGoodsWarehousing($condition)
{
$result = model('supply_goods_warehousing')->delete($condition);
return $result;
}
/**
*商品入库 - 生成本平台商品信息
* @param $goodsDetail
* @return array
*/
public function Generate1688GoodsInfo($goodsDetail, $template_id = 0, $saleType = 'normal')
{
$sku = [];
if (isset($goodsDetail['skuInfos'])) {
$sku = $goodsDetail['skuInfos'];// 商品规格列表
}
$fileList = $goodsDetail['image']['images'] ?? [];// 商品主图列表
$extend_goods_id = $goodsDetail['productID'];
$brandId = '';
$goods_id = $goodsDetail['goods_id'] ?? '';
$goods_name = $goodsDetail['subject'];
$categoryID = $goodsDetail['categoryID'];
$category_arr = [
'site_id' => 0,
'extend_id' => $categoryID,
'category_id_3' => 1688,
'category_name' => $goodsDetail['categoryName'],
];
$category_info = $this->getCreateCategory($categoryID, 'category_id,category_id_1,category_id_2,category_id_3,category_name', $category_arr);
$category_array = [];
if ($category_info['category_id_1'] > 0) {
$category_array[] = $category_info['category_id_1'];
}
if ($category_info['category_id_2'] > 0) {
$category_array[] = $category_info['category_id_2'];
}
if ($category_info['category_id_3'] > 0) {
$category_array[] = $category_info['category_id_3'];
}
$category_array[] = $category_info['category_id'];
$price_template = [
'price_set' => [
'multiple' => 5,
'increase' => 0,
],
'title_set' => [],
'sku_set' => [],
];
if ($template_id) {
$template = model('supply_price_template')->getInfo(['id' => $template_id]);
if ($template) {
$price_template['price_set'] = json_decode($template['price_set'], true);
$price_template['title_set'] = json_decode($template['title_set'], true);
$price_template['sku_set'] = json_decode($template['sku_set'], true);
}
} else {
$template = model('supply_price_template')->getInfo(['site_id' => $this->site_id, 'is_default' => 1]);
if ($template) {
$price_template['price_set'] = json_decode($template['price_set'], true);
$price_template['title_set'] = json_decode($template['title_set'], true);
$price_template['sku_set'] = json_decode($template['sku_set'], true);
}
}
// 数据处理 - 库存
$saleInfo = $goodsDetail['saleInfo'];
$stock = $saleInfo['amountOnSale'];
$img_url = 'https://cbu01.alicdn.com/';
// 数据处理 - 主图列表
$goodsImage = implode(',', array_map(function ($data) use ($img_url) {
return $img_url . $data;
}, $fileList));
$default_img = explode(',', $goodsImage)[0];
$attributes = array_column($sku, 'attributes');
$_spec = [];
foreach ($attributes as $key => $val) {
foreach ($val as $k => $v) {
$attributeID = $v['attributeID'];
$skuImageUrl = $v['skuImageUrl'] ?? '';
$spec_value_name = $v['attributeValue'];
if (!isset($_spec[$attributeID])) {
$_spec[$attributeID] = [
'spec_id' => $attributeID,
'spec_name' => $v['attributeName'],
'value' => [$spec_value_name => [
'spec_id' => $attributeID,
'spec_name' => $v['attributeName'],
'spec_value_name' => $v['attributeValue'],
'spec_value_id' => $attributeID + $key,
'image' => $skuImageUrl ? $img_url . $skuImageUrl : ''
]]
];
} else {
$_spec[$attributeID]['value'][$spec_value_name] = [
'spec_id' => $attributeID,
'spec_name' => $v['attributeName'],
'spec_value_name' => $v['attributeValue'],
'spec_value_id' => $attributeID + $key,
'image' => $skuImageUrl ? $img_url . $skuImageUrl : ''
];
}
}
}
if (count($sku) > 0) {//多规格
$skuList = $this->generateGoodsSkuInfo($sku, $goods_id, $saleInfo, $price_template, $default_img, $img_url, $_spec, $goodsDetail['productID'], $saleType);
$one_sku = $sku[0];
if ($saleType == 'normal') {
$minOrderQuantity = 1;
$consignPrice = $one_sku['retailPrice'];
$is_free_shipping = 1;
} else {
$minOrderQuantity = $saleInfo['minOrderQuantity'];
$consignPrice = $one_sku['jxhyPfPrice'];
$is_free_shipping = 0;
}
} else { //单规格
if ($saleType == 'normal') {
$minOrderQuantity = 1;
$consignPrice = $saleInfo['retailprice'];
$is_free_shipping = 1;
} else {
$minOrderQuantity = $saleInfo['minOrderQuantity'];
$consignPrice = $saleInfo['jxhyPfPrice'];
$is_free_shipping = 0;
}
// $startQuantity = array_column($goodsDetail['saleInfo']['priceRanges'], 'startQuantity');
// $price = $saleInfo['priceRanges'][array_search(min($startQuantity), $startQuantity)]['price'] ?? $saleInfo['priceRanges'][0]['price'];
$price = $consignPrice;
$image = $goodsDetail['image']['images'][0];
//单规格单独去拼装
$skuList = [$this->fictitiousGoodsSkuInfo($goods_id, $goods_name, $consignPrice, $consignPrice, $stock, $image, $img_url, $goodsDetail)];
$one_sku = [
'retailPrice' => $consignPrice,
'consignPrice' => $consignPrice,
'price' => $price
];
}
$_spec = array_map(function ($val) {
return [
'spec_id' => $val['spec_id'],
'spec_name' => $val['spec_name'],
'value' => array_values($val['value'])
];
}, $_spec);
if ($_spec) {
$this->goods_spec_format = json_encode(array_values($_spec), JSON_UNESCAPED_UNICODE);
}
$goods_attr_format = [];
if ($goodsDetail['attributes']) {
foreach ($goodsDetail['attributes'] as $key => $val) {
$goods_attr_format[] = [
'attr_class_id' => $key,
'attr_id' => $val['attributeID'],
'attr_name' => $val['attributeName'],
'attr_value_id' => $val['attributeID'],
'attr_value_name' => $val['value'],
'sort' => $key,
];
}
}
$goods_content = $goodsDetail['description'];//商品详情
$mul_inc_price = $price_template['price_set']['multiple'] ?? 0;
if ($mul_inc_price) {
$inc_price = ($consignPrice * $mul_inc_price / 100);
$inc_price = $inc_price < 0.01 ? 0.01 : $inc_price;
} else {
$inc_price = ($price_template['price_set']['increase'] ?: $consignPrice * 5 / 100);
$inc_price = $inc_price < 0.01 ? 0.01 : $inc_price;
}
$price = $consignPrice + $inc_price;
$title_set = $price_template['title_set'] ?? '';
if ($title_set) {
if (isset($title_set['delete_keywords']) && $title_set['delete_keywords']) {
$goods_name = str_replace($title_set['delete_keywords'], '', $goods_name);
}
$goods_name = $title_set['prefix'] . $goods_name . $title_set['suffix'];
}
$category_id = ',' . implode(',', $category_array) . ',';
$category_array = [implode(',', $category_array)];
$category_json = json_encode($category_array);//商品分类
$goodsData = [
'goods_id' => $goods_id,
'extend_goods_id' => $extend_goods_id,
'goods_name' => $goods_name,// 商品名称,
'goods_attr_class' => input("goods_attr_class", ""),// 商品类型id,
'goods_attr_name' => input("goods_attr_name", ""),// 商品类型名称,
'category_id' => $category_id,
'category_name' => $category_arr['category_name'],//商品分类数组
'category_array' => $category_array,//商品分类数组
'category_json' => $category_json,
'goods_image' => $goodsImage,// 商品主图路径
'goods_content' => $goodsDetail['description'] ?: $goods_content,// 商品详情,
'goods_state' => $goodsDetail['status'] == 'published' ? 1 : 0,// 【固定不变】
'price' => moneyFormat(round($price, 1)),// 商品价格取第一个sku 对应-建议零售价,// 商品价格取第一个sku
'market_price' => moneyFormat(round($price + $price * 35 / 100, 1)),//划线价
'cost_price' => $one_sku['consignPrice'] ?? $one_sku['price'] ?? 0,// 成本价取第一个sku 对应-结算价
'sku_no' => input("sku_no", ""),// 商品sku编码
'weight' => input("weight", ""),// 重量
'volume' => input("volume", ""),// 体积
'goods_stock' => $stock,// 商品库存(总和)
'goods_stock_alarm' => 0,// 库存预警
'is_free_shipping' => $is_free_shipping,// 是否免邮
'shipping_template' => 0,// 指定运费模板
'goods_spec_format' => $this->goods_spec_format,// 商品规格格式
'goods_attr_format' => json_encode($goods_attr_format, JSON_UNESCAPED_UNICODE),// 商品属性格式
'introduction' => input("introduction", ""),// 促销语
'keywords' => input("keywords", ""),// 关键词
'unit' => $saleInfo['unit'],// 单位
'video_url' => $goodsDetail['mainVedio'] ?? '',// 视频
'goods_sku_data' => json_encode($skuList, JSON_UNESCAPED_UNICODE),// SKU商品数据
'channel_type' => 1688,// 限购
'max_buy' => 0,// 限购
'min_buy' => $minOrderQuantity,// 起售
'spec_type_status' => input('spec_type_status', 0),
'site_id' => $this->supply_site_id,
'site_name' => $this->SupplyInfo['title'],
'website_id' => $this->SupplyInfo['website_id'],
'is_own' => 1,//是否自营
'verify_state' => 1,//是否审核
'timer_on' => 0,//定时上架
'timer_off' => 0,//定时下架
'brand_id' => $brandId,//品牌id
'brand_name' => '',//品牌名称
];
return $goodsData;
}
/***
* @param $category_id
* @param $field
* @param $model
* @return mixed|void
*/
public function getCreateCategory($category_id, $field = '*', $category = [])
{
$list = model('supply_goods_category')->getInfo([['site_id', '=', 0], ['extend_id', '=', $category_id]], $field);
if (empty($list)) {
model('supply_goods_category')->add($category);
return $this->getCreateCategory($category_id, $field, $category);
} else {
return $list;
}
}
/***
* 添加产品
* @param $goodsData
* @param $site_id
* @param $productID
* @param $template_id
* @return array
*/
public function addGoods($goodsData, $site_id, $productID, $template_id = 0, $cloud_id = '')
{
model('goods')->startTrans();
try {
$channel_type = $goodsData['channel_type'] ?: 'own';
$third_party_name= $channel_type == 'own' ? '自营平台' : '第三方平台';
$appid='';
if ($cloud_id) {
$cloud_model = new CloudApi($cloud_id);
$cloud_config = $cloud_model->getConfig();
$third_party_name=$cloud_config['app_name'];
$channel_type='third';
$appid=$cloud_config['app_id'];
$follow = $cloud_model->followGoods($productID, $goodsData['channel_type'])['data'];
if ($follow['message'] != 'ok') throw new \Exception('添加关注失败');
}
$this->site_id = $site_id;
// 判断:当前商品是否已经入库
$where=[['open_offer_id', '=', $productID], ['site_id', '=', $this->site_id]];
if($cloud_id){
$where[] = ['cloud_id', '=', $cloud_id];
}
$isHas = (int)model("supply_goods_warehousing")->getValue($where, 'id');
if ($isHas) throw new \Exception('当前商品已经存在,您可以直接编辑商品或者删除重新添加');
$goodsData['site_id'] = $site_id;
$goods_image = explode(',', $goodsData['goods_image']);
$goods_sku_data = json_decode($goodsData['goods_sku_data'], true);
$sku_image = array_column($goods_sku_data, 'sku_image');
$goods_images = array_unique(array_merge($goods_image, $sku_image));
$this->GooodsImgCheck($site_id, $goods_images);//验证图片上传
$res = (new GoodsModel())->addGoods($goodsData);
if ($res['data']) {
model('supply_goods_warehousing')->add([
'site_id' => $this->site_id,
'appid' => $appid,
'goods_id' => $res['data'],
'open_offer_id' => $productID,
'channel_type' => $channel_type,
'third_party_name' => $third_party_name,
'template_id' => $template_id,
'sku_image' => $goods_image[0],
'goods_name' => $goodsData['goods_name'],
'cloud_id' => $cloud_id,
'create_time' => time(),
'update_time' => time(),
]);
model('goods')->commit();
return $this->success('入库成功');
}
throw new \Exception($res['message']);
} catch (\Exception $e) {
model('goods')->rollback();
return $this->error('', $e->getMessage());
}
}
/**
* Common: 商品入库 - 生成本平台商品规格信息
* @param $goodsDetail
* @param $goodsId
* @return array|array[]
*/
private function generateGoodsSkuInfo($sku, $goodsId, $saleInfo, $price_template, $defaultSkuImage, $img_url, $_spec, $offerId, $saleType = '')
{
// 获取默认主图
// 处理规格信息 生成本平台规矩信息列表
$skuList = array_map(function ($skuItem) use ($goodsId, $saleInfo, $defaultSkuImage, $price_template, $img_url, $_spec, $offerId, $saleType) {
if ($saleType == 'normal') {
$consignPrice = $skuItem['retailPrice'];
} else {
$consignPrice = $skuItem['jxhyPfPrice'];
}
$mul_inc_price = $price_template['price_set']['multiple'] ?? 0;
if ($mul_inc_price) {
$inc_price = ($skuItem['retailPrice'] * $mul_inc_price / 100);
$inc_price = $inc_price < 0.01 ? 0.01 : $inc_price;
} else {
$inc_price = ($price_template['price_set']['increase'] ?: $skuItem['retailPrice'] * 5 / 100);
$inc_price = $inc_price < 0.01 ? 0.01 : $inc_price;
}
$sku_set = $price_template['sku_set'] ?? '';
$price = $consignPrice + $inc_price;
$price = ceil($price * 10) / 10;
$attributes = $skuItem['attributes'];
$attributes = array_map(function ($item) use ($_spec) {
$spec_value_id = $_spec[$item['attributeID']]['value'][$item['attributeValue']]['spec_value_id'];
return [
'spec_id' => $item['attributeID'],
'spec_name' => $item['attributeName'],
'spec_value_id' => $spec_value_id,
'spec_value_name' => $item['attributeValue'],
'image' => '',
];
}, $attributes);
$sku_name = $skuItem['cargoNumber'];
if ($sku_set) {
if (isset($sku_set['delete_keywords']) && $sku_set['delete_keywords']) {
$sku_name = str_replace($sku_set['delete_keywords'], '', $sku_name);
}
$sku_name = $sku_set['prefix'] . $sku_name . $sku_set['suffix'];
}
$price_json = [
[
'num' => 1,
'price' => $price,
]
];
// 规格列表
return [
'site_id' => $this->supply_site_id,// 所属店铺id
'goods_id' => $goodsId,// 商品id
'sku_id' => '',// 商品id
'sku_name' => $sku_name,// 商品sku名称
'sku_no' => $skuItem['skuCode'],// 商品sku编码
'price' => $price, // sku单价
'cost_price' => $consignPrice,//sku成本价
'price_json' => json_encode($price_json),
'stock' => $skuItem['amountOnSale'], // 商品sku库存
'sku_image' => isset($skuItem['attributes'][0]['skuImageUrl']) ? $img_url . $skuItem['attributes'][0]['skuImageUrl'] : $defaultSkuImage,
'sku_images' => isset($skuItem['attributes'][0]['skuImageUrl']) ? $img_url . $skuItem['attributes'][0]['skuImageUrl'] : $defaultSkuImage,
'goods_class' => 1,
'goods_class_name' => '实物商品',
'create_time' => time(),
'modify_time' => time(),
'goods_attr_class' => 0,
'is_default' => 0,
'spec_name' => $skuItem['cargoNumber'] ?? '', //
'real_stock' => $skuItem['amountOnSale'], // 实物库存
'sku_spec_format' => $attributes,
'goods_supplier_format' => json_encode([
'offerId' => $offerId,
'skuId' => $skuItem['skuId'],
'spec_id' => $skuItem['specId'],
'saleType' => $saleType,
]),
'extend_sku_id' => $skuItem['specId'], // 必须内容
'market_price' => moneyFormat(round($price + $price * 35 / 100, 1)),
'weight' => 0,
'volume' => 0,
'sale_num' => 0,
'stock_alarm' => '',
];
}, $sku);
if ($goodsId) {
$goods_model = new Goods();
$goods_sku_list = $goods_model->getGoodsSkuList([['goods_id', '=', $goodsId], ['site_id', '=', $this->supply_site_id]], "sku_id,sku_name,sku_no,sku_spec_format,price,market_price,cost_price,stock,weight,volume,sku_image,sku_images,goods_spec_format,spec_name,stock_alarm,is_default,goods_supplier_format", '')['data'];
$mpsku_arr = array_column($skuList, null, 'sku_no');
foreach ($goods_sku_list as $key => &$skuItem) {
if (isset($mpsku_arr[$skuItem['sku_no']])) {
$skuItem = array_merge($skuItem, $mpsku_arr[$skuItem['sku_no']]);
}
}
return $goods_sku_list;
}
return $skuList ?? [];
}
//1688单规格拼装数据
private function fictitiousGoodsSkuInfo($goodsId, $goodsName, $price, $retailPrice, $amountOnSale, $image, $img_url, $goodsDetail = [], $saleType = '')
{
$offerId = $goodsDetail['productID'];
$price_json = [
[
'num' => 1,
'price' => $price,
]
];
return [
'site_id' => $this->supply_site_id,// 所属店铺id
'goods_id' => $goodsId,// 商品id
'sku_id' => '',// 商品id
'sku_name' => $goodsName,// 商品sku名称
'sku_no' => '',// 商品sku编码
'price' => round(moneyFormat($price), 1, PHP_ROUND_HALF_EVEN), // sku单价
'cost_price' => $retailPrice,//sku成本价
'price_json' => json_encode($price_json),
'stock' => $amountOnSale, // 商品sku库存
'sku_image' => $img_url . $image,
'sku_images' => $img_url . $image,
'goods_class' => 1,
'goods_class_name' => '实物商品',
'create_time' => time(),
'modify_time' => time(),
'goods_attr_class' => 0,
'is_default' => 0,
'spec_name' => '', //
'real_stock' => $amountOnSale, // 实物库存
'sku_spec_format' => '',
'goods_supplier_format' => json_encode([
'offerId' => $offerId,
'skuId' => '',
'spec_id' => '',
'saleType' => $saleType,
]),//第三方扩展数据,因为是单规格为空
'extend_sku_id' => $offerId,
// 必须内容
'market_price' => moneyFormat(round($price + $price * 35 / 100, 1)),
'weight' => 0,
'volume' => 0,
'sale_num' => 0,
'virtual_sale' => 0,
'stock_alarm' => '',
];
}
/****
* 检查图片同步
* @param $goods_images
* @return void
*/
public function GooodsImgCheck($site_id, $goods_images)
{
$thumb_value = model('album_pic')->getColumn([['pic_path', 'in', $goods_images]], 'pic_path', 'pic_path');
$goods_images = array_diff($goods_images, $thumb_value);
if ($goods_images) {
$album_id = model('album')->getValue([['site_id', '=', $site_id], ['type', '=', 'img']], 'album_id');
$album_model = new Album();
$cron = new Cron();
foreach ($goods_images as $k => $v) {
$data = [
"pic_path" => $v,//图片云存储
"pic_name" => md5($v),
"pic_spec" => 'x',
"update_time" => time(),
"site_id" => $site_id,
"size" => 0,
"album_id" => $album_id,
"is_thumb" => 0,
];
$res = $album_model->addAlbumPic($data);
if ($res['code'] >= 0) {
$data["id"] = $res["data"];
$cron->addCron(1, 1, '图片同步上传', 'AlbumUpload', time(), $res["data"]);
}
}
}
return $this->success('成功');
}
}