编码自动化

This commit is contained in:
2025-09-16 09:49:16 +08:00
parent e41be712d3
commit 48bd9c516d
2 changed files with 79 additions and 0 deletions
+36
View File
@@ -48,11 +48,47 @@ class VehColorService
);
}
/**
* 生成唯一的7位颜色编码
* 格式:C + (O/I) + 5位字母数字组合
*
* @param int $type 类型:2=I,其他=O
* @return string 7位唯一编码
*/
public function generateUniqueColorCode($type)
{
$secondChar = $type ==2 ? 'I' : 'O';
$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 = 'C' . $secondChar . $suffix;
// 检查是否已存在
$existing = VehColor::where('color_code', $colorCode)->first();
if (!$existing) {
return $colorCode;
}
}
// 如果1000次尝试后仍然重复,使用时间戳确保唯一性
$timestamp = substr(time(), -5);
return 'C' . $secondChar . $timestamp;
}
/**
* 添加前置处理
*/
public function beforeServiceStore($data, Request $request)
{
$type = $data['type'] ?? 0;
$data['color_code'] = $this->generateUniqueColorCode($type);
$data['created_by'] = $request->user->uid;
$data['updated_by'] = $request->user->uid;
return $data;
@@ -80,4 +80,47 @@ class VehModificationService
return $config;
}
/**
* 生成唯一的7位颜色编码
* 格式:C + (O/I) + 5位字母数字组合
*
* @param int $type 类型
* @return string 7位唯一编码
*/
public function generateUniqueModificationCode($type)
{
$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)];
}
$code = 'C' . $type . $suffix;
// 检查是否已存在
$existing = VehModification::where('code', $code)->first();
if (!$existing) {
return $code;
}
}
// 如果1000次尝试后仍然重复,使用时间戳确保唯一性
$timestamp = substr(time(), -5);
return 'C' . $type . $timestamp;
}
/**
* 添加前置处理
*/
public function beforeServiceStore($data, Request $request)
{
$type = $data['type'] ?? 0;
$data['code'] = $this->generateUniqueModificationCode($type);
return $data;
}
}