sku
This commit is contained in:
@@ -2,9 +2,12 @@
|
||||
|
||||
namespace app\common\service;
|
||||
|
||||
use app\common\model\SkuAttributeValue;
|
||||
use app\common\validate\SkuValidate;
|
||||
use app\common\traits\crud\CrudServiceTrait;
|
||||
use app\common\model\Sku;
|
||||
use support\Redis;
|
||||
use support\Request;
|
||||
|
||||
class SkuService
|
||||
{
|
||||
@@ -28,4 +31,85 @@ class SkuService
|
||||
{
|
||||
return new $this->validator;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 添加前置处理
|
||||
*/
|
||||
public function beforeServiceStore($data, Request $request)
|
||||
{
|
||||
$spec = [];
|
||||
foreach ($data['spec'] as $key => $value) {
|
||||
$specItem = [];
|
||||
$specItem['category_id'] = $data['category_id'];
|
||||
$specItem['attr_id'] = $value['attr_id'];
|
||||
$specItem['attr_name'] = $value['attr_name'];
|
||||
$specItem['attr_value'] = $value['attr_value'];
|
||||
$spec[] = $specItem;
|
||||
}
|
||||
$spec_json = json_encode($spec,JSON_UNESCAPED_UNICODE);
|
||||
Redis::set('sku_attr_'.$request->user->uid, $spec_json,30);
|
||||
|
||||
unset($data['spec']);
|
||||
$data['spec_json'] = $spec_json;
|
||||
$data['user_id'] = $request->user->uid;
|
||||
$data['code'] = $this->generateUniqueCode();
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 添加后置处理
|
||||
*/
|
||||
public function afterServiceStore($res)
|
||||
{
|
||||
$specs = Redis::get('sku_attr_'.$res['user_id']);
|
||||
$specs= json_decode($specs,true);
|
||||
var_dump($specs);
|
||||
$spec = [];
|
||||
foreach ($specs as $key => $value) {
|
||||
$spec['category_id'] = $res['category_id'];
|
||||
$spec['sku_id'] = $res['id'];
|
||||
$spec['attr_id'] = $value['attr_id'];
|
||||
$spec['attr_name'] = $value['attr_name'];
|
||||
$spec['attr_value'] = $value['attr_value'];
|
||||
SkuAttributeValue::create($spec);
|
||||
}
|
||||
return $res;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 生成唯一的7位颜色编码
|
||||
* 格式:C + (O/I) + 5位字母数字组合
|
||||
*
|
||||
* @param int $type 类型:2=I,其他=O
|
||||
* @return string 7位唯一编码
|
||||
*/
|
||||
public function generateUniqueCode()
|
||||
{
|
||||
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
$maxAttempts = 10; // 防止无限循环
|
||||
|
||||
for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
|
||||
// 生成后5位随机字符
|
||||
$suffix = '';
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$suffix .= $chars[rand(0, strlen($chars) - 1)];
|
||||
}
|
||||
|
||||
$colorCode = 'PN' . $suffix;
|
||||
|
||||
// 检查是否已存在
|
||||
$existing = Sku::where('code', $colorCode)->first();
|
||||
if (!$existing) {
|
||||
return $colorCode;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果1000次尝试后仍然重复,使用时间戳确保唯一性
|
||||
$timestamp = substr(time(), -5);
|
||||
return 'PN' . $timestamp;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user