add sku mapping

This commit is contained in:
2026-04-14 13:45:28 +08:00
parent b647680576
commit b1cd4ea0eb
16 changed files with 3176 additions and 0 deletions
@@ -0,0 +1,567 @@
<?php
declare(strict_types=1);
namespace App\Controller\Api\V1;
use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Middleware\PermissionMiddleware;
use App\Model\SkuMapping;
use App\Model\SkuOrigin;
use App\Model\Store;
use App\Service\OperationLogService;
use App\Service\SkuService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;
/**
* SKU 平台映射管理接口
*/
#[OA\Tag(name: 'SkuMappings', description: 'SKU 平台映射管理')]
#[Controller(prefix: "/api/v1/sku-mappings")]
#[Middleware(AuthMiddleware::class)]
#[Middleware(PermissionMiddleware::class)]
class SkuMappingController extends AbstractController
{
public function __construct(
protected readonly SkuService $skuService,
) {}
/**
* 映射列表
*/
#[OA\Get(
path: '/sku-mappings',
summary: 'SKU 映射列表',
description: '获取 SKU 平台映射列表,支持分页和多维度筛选',
security: [['bearerAuth' => []]],
tags: ['SkuMappings'],
parameters: [
new OA\Parameter(name: 'page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 1)),
new OA\Parameter(name: 'per_page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 15, maximum: 100)),
new OA\Parameter(name: 'company_id', in: 'query', required: false, description: '公司 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
new OA\Parameter(name: 'platform_id', in: 'query', required: false, description: '平台 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
new OA\Parameter(name: 'store_id', in: 'query', required: false, description: '店铺 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
new OA\Parameter(name: 'origin_sku', in: 'query', required: false, description: '原始 SKU 模糊搜索', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'platform_outer_sku', in: 'query', required: false, description: '平台侧 SKU 模糊搜索', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'enabled', in: 'query', required: false, description: '启用状态', schema: new OA\Schema(type: 'boolean')),
],
responses: [
new OA\Response(
response: 200,
description: '获取成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '获取成功'),
new OA\Property(property: 'data', properties: [
new OA\Property(property: 'items', type: 'array', items: new OA\Items(ref: '#/components/schemas/SkuMapping')),
new OA\Property(property: 'total', type: 'integer', example: 100),
new OA\Property(property: 'page', type: 'integer', example: 1),
new OA\Property(property: 'per_page', type: 'integer', example: 15),
], type: 'object'),
])
),
new OA\Response(response: 401, description: '未认证', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
new OA\Response(response: 403, description: '无权限', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "", methods: "GET")]
public function index(): array
{
$query = SkuMapping::query()->select([
'id', 'company_id', 'platform_id', 'store_id', 'origin_sku',
'origin_sku_id', 'platform_outer_sku', 'platform_product_id',
'enabled', 'note', 'created_at', 'updated_at',
]);
$this->applyDataScope($query);
// 筛选条件
$filters = [
'company_id' => 'exact',
'platform_id' => 'exact',
'store_id' => 'exact',
];
foreach ($filters as $field => $type) {
$value = $this->request->input($field);
if ($value !== null && $value !== '') {
$query->where($field, (int) $value);
}
}
$origin_sku = $this->request->input('origin_sku');
if ($origin_sku !== null && $origin_sku !== '') {
$query->where('origin_sku', 'ilike', "%{$origin_sku}%");
}
$platform_outer_sku = $this->request->input('platform_outer_sku');
if ($platform_outer_sku !== null && $platform_outer_sku !== '') {
$query->where('platform_outer_sku', 'ilike', "%{$platform_outer_sku}%");
}
$enabled = $this->request->input('enabled');
if ($enabled !== null && $enabled !== '') {
$query->where('enabled', filter_var($enabled, FILTER_VALIDATE_BOOLEAN));
}
$query->orderBy('created_at', 'desc');
$per_page = min(max((int) $this->request->input('per_page', 15), 1), 100);
$page = max((int) $this->request->input('page', 1), 1);
$total = $query->count();
$items = $query->offset(($page - 1) * $per_page)->limit($per_page)->get();
return [
'code' => 0,
'message' => '获取成功',
'data' => [
'items' => $items,
'total' => $total,
'page' => $page,
'per_page' => $per_page,
],
];
}
/**
* 检查重复映射
*/
#[OA\Get(
path: '/sku-mappings/check-duplicate',
summary: '检查同平台重复映射',
description: '检查指定 origin_sku 在某平台下是否已存在映射记录,帮助用户决定是否复用已有编码',
security: [['bearerAuth' => []]],
tags: ['SkuMappings'],
parameters: [
new OA\Parameter(name: 'origin_sku_id', in: 'query', required: true, description: '内部 SKU ID', schema: new OA\Schema(type: 'integer')),
new OA\Parameter(name: 'platform_id', in: 'query', required: true, description: '平台 ID', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(
response: 200,
description: '检查完成',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'data', properties: [
new OA\Property(property: 'has_duplicate', type: 'boolean', example: true),
new OA\Property(property: 'existing_mappings', type: 'array', items: new OA\Items(type: 'object')),
new OA\Property(property: 'message', type: 'string'),
], type: 'object'),
])
),
new OA\Response(response: 422, description: '参数校验失败', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "check-duplicate", methods: "GET")]
public function checkDuplicate(): ResponseInterface|array
{
$origin_sku_id = $this->request->input('origin_sku_id');
$platform_id = $this->request->input('platform_id');
if (!$origin_sku_id || !$platform_id) {
return $this->response->json([
'code' => 422,
'message' => '缺少必填参数: origin_sku_id, platform_id',
])->withStatus(422);
}
$result = $this->skuService->checkDuplicate((int) $origin_sku_id, (int) $platform_id);
return [
'code' => 0,
'message' => 'success',
'data' => $result,
];
}
/**
* 自动生成 platform_outer_sku
*/
#[OA\Post(
path: '/sku-mappings/generate-sku',
summary: '自动生成平台侧 SKU',
description: '根据指定策略自动生成 platform_outer_sku,同时返回重复检测结果',
security: [['bearerAuth' => []]],
tags: ['SkuMappings'],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['origin_sku_id', 'platform_id', 'strategy'],
properties: [
new OA\Property(property: 'origin_sku_id', type: 'integer', example: 1),
new OA\Property(property: 'platform_id', type: 'integer', example: 1),
new OA\Property(property: 'strategy', type: 'string', enum: ['prefix', 'prefix_random', 'manual'], example: 'prefix'),
new OA\Property(property: 'prefix', type: 'string', example: 'C03'),
new OA\Property(property: 'random_length', type: 'integer', example: 4),
new OA\Property(property: 'manual_value', type: 'string', nullable: true),
]
)
),
responses: [
new OA\Response(
response: 200,
description: '生成成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'data', properties: [
new OA\Property(property: 'generated_sku', type: 'string', example: 'C03_0032'),
new OA\Property(property: 'strategy_record', type: 'string', example: 'prefix:C03'),
new OA\Property(property: 'has_duplicate', type: 'boolean'),
new OA\Property(property: 'existing_mappings', type: 'array', items: new OA\Items(type: 'object')),
new OA\Property(property: 'message', type: 'string'),
], type: 'object'),
])
),
new OA\Response(response: 422, description: '参数校验失败', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "generate-sku", methods: "POST")]
public function generateSku(): ResponseInterface|array
{
$data = $this->request->all();
$required = ['origin_sku_id', 'platform_id', 'strategy'];
foreach ($required as $field) {
if (!isset($data[$field]) || $data[$field] === '') {
return $this->response->json([
'code' => 422,
'message' => "缺少必填参数: {$field}",
])->withStatus(422);
}
}
$origin_sku_id = (int) $data['origin_sku_id'];
$platform_id = (int) $data['platform_id'];
$strategy = $data['strategy'];
$prefix = $data['prefix'] ?? '';
$random_length = (int) ($data['random_length'] ?? 4);
$manual_value = $data['manual_value'] ?? null;
// 查找 origin_sku 记录
$sku_origin = SkuOrigin::query()->find($origin_sku_id);
if (!$sku_origin) {
return $this->response->json([
'code' => 422,
'message' => '指定的内部 SKU 不存在',
])->withStatus(422);
}
// 生成 platform_outer_sku
$generated_sku = $this->skuService->generatePlatformOuterSku(
strategy: $strategy,
origin_sku: $sku_origin->sku,
prefix: $prefix,
random_length: $random_length,
manual_value: $manual_value,
);
$strategy_record = $this->skuService->buildStrategyRecord($strategy, $prefix, $random_length);
// 检查重复
$duplicate_check = $this->skuService->checkDuplicate($origin_sku_id, $platform_id);
return [
'code' => 0,
'message' => 'success',
'data' => [
'generated_sku' => $generated_sku,
'strategy_record' => $strategy_record,
'has_duplicate' => $duplicate_check['has_duplicate'],
'existing_mappings' => $duplicate_check['existing_mappings'],
'message' => $duplicate_check['message'],
],
];
}
/**
* 映射详情
*/
#[OA\Get(
path: '/sku-mappings/{id}',
summary: 'SKU 映射详情',
security: [['bearerAuth' => []]],
tags: ['SkuMappings'],
parameters: [
new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(
response: 200,
description: '获取成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '获取成功'),
new OA\Property(property: 'data', ref: '#/components/schemas/SkuMapping'),
])
),
new OA\Response(response: 404, description: '数据不存在', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "{id}", methods: "GET")]
public function show(int $id): ResponseInterface|array
{
$query = SkuMapping::query();
$this->applyDataScope($query);
$record = $query->where('id', $id)->first();
if (!$record) {
return $this->response->json([
'code' => 404,
'message' => '数据不存在',
])->withStatus(404);
}
return [
'code' => 0,
'message' => '获取成功',
'data' => $record,
];
}
/**
* 创建映射
*/
#[OA\Post(
path: '/sku-mappings',
summary: '创建 SKU 映射',
security: [['bearerAuth' => []]],
tags: ['SkuMappings'],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['company_id', 'platform_id', 'origin_sku', 'platform_product_id'],
properties: [
new OA\Property(property: 'company_id', type: 'integer', example: 3),
new OA\Property(property: 'platform_id', type: 'integer', example: 1),
new OA\Property(property: 'store_id', type: 'integer', nullable: true, example: 101),
new OA\Property(property: 'origin_sku', type: 'string', example: '0032'),
new OA\Property(property: 'origin_sku_id', type: 'integer', nullable: true, example: 1),
new OA\Property(property: 'platform_product_id', type: 'string', example: 'ITEM-001'),
new OA\Property(property: 'platform_outer_sku', type: 'string', nullable: true, example: 'C03_0032'),
new OA\Property(property: 'generation_strategy', type: 'string', nullable: true, example: 'prefix:C03'),
new OA\Property(property: 'warehouse_id', type: 'integer', nullable: true),
new OA\Property(property: 'enabled', type: 'boolean', example: true),
new OA\Property(property: 'note', type: 'string', nullable: true),
]
)
),
responses: [
new OA\Response(
response: 201,
description: '创建成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '创建成功'),
new OA\Property(property: 'data', ref: '#/components/schemas/SkuMapping'),
])
),
new OA\Response(response: 422, description: '参数校验失败', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "", methods: "POST")]
public function store(): ResponseInterface|array
{
$data = $this->request->all();
$required_fields = ['company_id', 'platform_id', 'origin_sku', 'platform_product_id'];
foreach ($required_fields as $field) {
if (!isset($data[$field]) || $data[$field] === '') {
return $this->response->json([
'code' => 422,
'message' => "缺少必填字段: {$field}",
])->withStatus(422);
}
}
$record = SkuMapping::query()->create([
'company_id' => (int) $data['company_id'],
'platform_id' => (int) $data['platform_id'],
'store_id' => isset($data['store_id']) ? (int) $data['store_id'] : null,
'origin_sku' => $data['origin_sku'],
'origin_sku_id' => isset($data['origin_sku_id']) ? (int) $data['origin_sku_id'] : null,
'platform_product_id' => $data['platform_product_id'],
'platform_outer_sku' => $data['platform_outer_sku'] ?? null,
'generation_strategy' => $data['generation_strategy'] ?? null,
'warehouse_id' => isset($data['warehouse_id']) ? (int) $data['warehouse_id'] : null,
'enabled' => $data['enabled'] ?? true,
'note' => $data['note'] ?? null,
]);
$user_id = OperationLogService::getCurrentUserId();
if ($user_id) {
OperationLogService::log(
$user_id,
'create',
'sku_mapping',
$record->id,
'创建 SKU 映射: ' . $data['origin_sku'] . ' → ' . ($data['platform_outer_sku'] ?? 'N/A'),
ip: $this->request->getHeaderLine('x-real-ip') ?: null,
);
}
return $this->response->json([
'code' => 0,
'message' => '创建成功',
'data' => $record,
])->withStatus(201);
}
/**
* 更新映射
*/
#[OA\Put(
path: '/sku-mappings/{id}',
summary: '更新 SKU 映射',
security: [['bearerAuth' => []]],
tags: ['SkuMappings'],
parameters: [
new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(properties: [
new OA\Property(property: 'origin_sku', type: 'string'),
new OA\Property(property: 'origin_sku_id', type: 'integer', nullable: true),
new OA\Property(property: 'platform_product_id', type: 'string'),
new OA\Property(property: 'platform_outer_sku', type: 'string', nullable: true),
new OA\Property(property: 'generation_strategy', type: 'string', nullable: true),
new OA\Property(property: 'store_id', type: 'integer', nullable: true),
new OA\Property(property: 'warehouse_id', type: 'integer', nullable: true),
new OA\Property(property: 'enabled', type: 'boolean'),
new OA\Property(property: 'note', type: 'string', nullable: true),
])
),
responses: [
new OA\Response(
response: 200,
description: '更新成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '更新成功'),
new OA\Property(property: 'data', ref: '#/components/schemas/SkuMapping'),
])
),
new OA\Response(response: 404, description: '数据不存在', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "{id}", methods: "PUT")]
public function update(int $id): ResponseInterface|array
{
$query = SkuMapping::query();
$this->applyDataScope($query);
$record = $query->where('id', $id)->first();
if (!$record) {
return $this->response->json([
'code' => 404,
'message' => '数据不存在',
])->withStatus(404);
}
$data = $this->request->all();
$allowed_fields = [
'origin_sku', 'origin_sku_id', 'platform_product_id', 'platform_outer_sku',
'generation_strategy', 'store_id', 'warehouse_id', 'enabled', 'note',
];
$update_data = array_intersect_key($data, array_flip($allowed_fields));
$record->update($update_data);
$user_id = OperationLogService::getCurrentUserId();
if ($user_id) {
OperationLogService::log(
$user_id,
'update',
'sku_mapping',
$record->id,
"更新 SKU 映射 #{$record->id}",
detail: ['updated_fields' => array_keys($update_data)],
ip: $this->request->getHeaderLine('x-real-ip') ?: null,
);
}
return [
'code' => 0,
'message' => '更新成功',
'data' => $record->fresh(),
];
}
/**
* 删除映射
*/
#[OA\Delete(
path: '/sku-mappings/{id}',
summary: '删除 SKU 映射',
security: [['bearerAuth' => []]],
tags: ['SkuMappings'],
parameters: [
new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(
response: 200,
description: '删除成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '删除成功'),
])
),
new OA\Response(response: 404, description: '数据不存在', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "{id}", methods: "DELETE")]
public function destroy(int $id): ResponseInterface|array
{
$query = SkuMapping::query();
$this->applyDataScope($query);
$record = $query->where('id', $id)->first();
if (!$record) {
return $this->response->json([
'code' => 404,
'message' => '数据不存在',
])->withStatus(404);
}
$record->delete();
$user_id = OperationLogService::getCurrentUserId();
if ($user_id) {
OperationLogService::log(
$user_id,
'delete',
'sku_mapping',
$id,
"删除 SKU 映射 #{$id}",
ip: $this->request->getHeaderLine('x-real-ip') ?: null,
);
}
return [
'code' => 0,
'message' => '删除成功',
];
}
/**
* DataScope 过滤
*/
private function applyDataScope(\Hyperf\Database\Model\Builder $query): void
{
$scope_type = $this->request->getAttribute('scope_type');
$scope_ids = $this->request->getAttribute('scope_ids', []);
if ($scope_type === 'store') {
$query->whereIn('store_id', $scope_ids);
} elseif ($scope_type === 'platform') {
$query->whereIn('platform_id', $scope_ids);
}
}
}
@@ -0,0 +1,450 @@
<?php
declare(strict_types=1);
namespace App\Controller\Api\V1;
use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Middleware\PermissionMiddleware;
use App\Model\SkuOrigin;
use App\Service\OperationLogService;
use App\Service\SkuService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use OpenApi\Attributes as OA;
use Psr\Http\Message\ResponseInterface;
/**
* 客户内部 SKU 管理接口
*/
#[OA\Tag(name: 'SkuOrigins', description: '客户内部 SKU 管理')]
#[Controller(prefix: "/api/v1/sku-origins")]
#[Middleware(AuthMiddleware::class)]
#[Middleware(PermissionMiddleware::class)]
class SkuOriginController extends AbstractController
{
public function __construct(
protected readonly SkuService $skuService,
) {}
/**
* SKU 列表
*/
#[OA\Get(
path: '/sku-origins',
summary: '客户内部 SKU 列表',
description: '获取客户内部 SKU 列表,支持分页和筛选',
security: [['bearerAuth' => []]],
tags: ['SkuOrigins'],
parameters: [
new OA\Parameter(name: 'page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 1)),
new OA\Parameter(name: 'per_page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 15, maximum: 100)),
new OA\Parameter(name: 'company_id', in: 'query', required: false, description: '公司 ID 精确筛选', schema: new OA\Schema(type: 'integer')),
new OA\Parameter(name: 'sku', in: 'query', required: false, description: 'SKU 编码模糊搜索', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'name', in: 'query', required: false, description: '产品名称模糊搜索', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'barcode', in: 'query', required: false, description: '条形码模糊搜索', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: '获取成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '获取成功'),
new OA\Property(property: 'data', properties: [
new OA\Property(property: 'items', type: 'array', items: new OA\Items(ref: '#/components/schemas/SkuOrigin')),
new OA\Property(property: 'total', type: 'integer', example: 100),
new OA\Property(property: 'page', type: 'integer', example: 1),
new OA\Property(property: 'per_page', type: 'integer', example: 15),
], type: 'object'),
])
),
new OA\Response(response: 401, description: '未认证', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
new OA\Response(response: 403, description: '无权限', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "", methods: "GET")]
public function index(): array
{
$query = SkuOrigin::query()->select([
'id', 'company_id', 'sku', 'barcode', 'name', 'label', 'hs', 'created_at', 'updated_at',
]);
// DataScope 过滤
$this->applyDataScope($query);
// 筛选条件
$company_id = $this->request->input('company_id');
if ($company_id !== null && $company_id !== '') {
$query->where('company_id', (int) $company_id);
}
$sku = $this->request->input('sku');
if ($sku !== null && $sku !== '') {
$query->where('sku', 'ilike', "%{$sku}%");
}
$name = $this->request->input('name');
if ($name !== null && $name !== '') {
$query->where(function ($q) use ($name): void {
$q->where('name', 'ilike', "%{$name}%")
->orWhere('label', 'ilike', "%{$name}%");
});
}
$barcode = $this->request->input('barcode');
if ($barcode !== null && $barcode !== '') {
$query->where('barcode', 'ilike', "%{$barcode}%");
}
$query->orderBy('created_at', 'desc');
// 分页
$per_page = min(max((int) $this->request->input('per_page', 15), 1), 100);
$page = max((int) $this->request->input('page', 1), 1);
$total = $query->count();
$items = $query->offset(($page - 1) * $per_page)->limit($per_page)->get();
return [
'code' => 0,
'message' => '获取成功',
'data' => [
'items' => $items,
'total' => $total,
'page' => $page,
'per_page' => $per_page,
],
];
}
/**
* SKU 详情
*/
#[OA\Get(
path: '/sku-origins/{id}',
summary: '客户内部 SKU 详情',
security: [['bearerAuth' => []]],
tags: ['SkuOrigins'],
parameters: [
new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(
response: 200,
description: '获取成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '获取成功'),
new OA\Property(property: 'data', ref: '#/components/schemas/SkuOrigin'),
])
),
new OA\Response(response: 404, description: '数据不存在', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "{id}", methods: "GET")]
public function show(int $id): ResponseInterface|array
{
$query = SkuOrigin::query();
$this->applyDataScope($query);
$record = $query->where('id', $id)->first();
if (!$record) {
return $this->response->json([
'code' => 404,
'message' => '数据不存在',
])->withStatus(404);
}
return [
'code' => 0,
'message' => '获取成功',
'data' => $record,
];
}
/**
* 创建 SKU
*/
#[OA\Post(
path: '/sku-origins',
summary: '创建客户内部 SKU',
security: [['bearerAuth' => []]],
tags: ['SkuOrigins'],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['company_id', 'sku', 'barcode', 'name'],
properties: [
new OA\Property(property: 'company_id', type: 'integer', example: 3),
new OA\Property(property: 'sku', type: 'string', example: '0032'),
new OA\Property(property: 'barcode', type: 'string', example: '6901234567890'),
new OA\Property(property: 'name', type: 'string', example: 'Running Shoes Model A'),
new OA\Property(property: 'label', type: 'string', nullable: true, example: '跑步鞋 A 款'),
new OA\Property(property: 'hs', type: 'string', nullable: true, example: '6403990090'),
new OA\Property(property: 'ledger', type: 'string', nullable: true),
new OA\Property(property: 'ext', type: 'object', nullable: true),
]
)
),
responses: [
new OA\Response(
response: 201,
description: '创建成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '创建成功'),
new OA\Property(property: 'data', ref: '#/components/schemas/SkuOrigin'),
])
),
new OA\Response(response: 422, description: '参数校验失败', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "", methods: "POST")]
public function store(): ResponseInterface|array
{
$data = $this->request->all();
// 参数校验
$required_fields = ['company_id', 'sku', 'barcode', 'name'];
foreach ($required_fields as $field) {
if (!isset($data[$field]) || $data[$field] === '') {
return $this->response->json([
'code' => 422,
'message' => "缺少必填字段: {$field}",
])->withStatus(422);
}
}
// 唯一性校验 (company_id + sku)
$exists = SkuOrigin::query()
->where('company_id', (int) $data['company_id'])
->where('sku', $data['sku'])
->exists();
if ($exists) {
return $this->response->json([
'code' => 422,
'message' => "该公司下 SKU '{$data['sku']}' 已存在",
])->withStatus(422);
}
$record = SkuOrigin::query()->create([
'company_id' => (int) $data['company_id'],
'sku' => $data['sku'],
'hs' => $data['hs'] ?? null,
'barcode' => $data['barcode'],
'name' => $data['name'],
'label' => $data['label'] ?? null,
'ledger' => $data['ledger'] ?? null,
'ext' => $data['ext'] ?? null,
]);
// 记录操作日志
$user_id = OperationLogService::getCurrentUserId();
if ($user_id) {
OperationLogService::log(
$user_id,
'create',
'sku_origin',
$record->id,
"创建内部 SKU: {$record->sku}",
ip: $this->request->getHeaderLine('x-real-ip') ?: null,
);
}
return $this->response->json([
'code' => 0,
'message' => '创建成功',
'data' => $record,
])->withStatus(201);
}
/**
* 更新 SKU
*/
#[OA\Put(
path: '/sku-origins/{id}',
summary: '更新客户内部 SKU',
security: [['bearerAuth' => []]],
tags: ['SkuOrigins'],
parameters: [
new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(properties: [
new OA\Property(property: 'sku', type: 'string'),
new OA\Property(property: 'barcode', type: 'string'),
new OA\Property(property: 'name', type: 'string'),
new OA\Property(property: 'label', type: 'string', nullable: true),
new OA\Property(property: 'hs', type: 'string', nullable: true),
new OA\Property(property: 'ledger', type: 'string', nullable: true),
new OA\Property(property: 'ext', type: 'object', nullable: true),
])
),
responses: [
new OA\Response(
response: 200,
description: '更新成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '更新成功'),
new OA\Property(property: 'data', ref: '#/components/schemas/SkuOrigin'),
])
),
new OA\Response(response: 404, description: '数据不存在', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
new OA\Response(response: 422, description: '参数校验失败', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "{id}", methods: "PUT")]
public function update(int $id): ResponseInterface|array
{
$query = SkuOrigin::query();
$this->applyDataScope($query);
$record = $query->where('id', $id)->first();
if (!$record) {
return $this->response->json([
'code' => 404,
'message' => '数据不存在',
])->withStatus(404);
}
$data = $this->request->all();
$allowed_fields = ['sku', 'barcode', 'name', 'label', 'hs', 'ledger', 'ext'];
$update_data = array_intersect_key($data, array_flip($allowed_fields));
// 如果修改了 sku,检查唯一性
if (isset($update_data['sku']) && $update_data['sku'] !== $record->sku) {
$exists = SkuOrigin::query()
->where('company_id', $record->company_id)
->where('sku', $update_data['sku'])
->where('id', '!=', $id)
->exists();
if ($exists) {
return $this->response->json([
'code' => 422,
'message' => "该公司下 SKU '{$update_data['sku']}' 已存在",
])->withStatus(422);
}
}
$record->update($update_data);
$user_id = OperationLogService::getCurrentUserId();
if ($user_id) {
OperationLogService::log(
$user_id,
'update',
'sku_origin',
$record->id,
"更新内部 SKU: {$record->sku}",
detail: ['updated_fields' => array_keys($update_data)],
ip: $this->request->getHeaderLine('x-real-ip') ?: null,
);
}
return [
'code' => 0,
'message' => '更新成功',
'data' => $record->fresh(),
];
}
/**
* 删除 SKU
*/
#[OA\Delete(
path: '/sku-origins/{id}',
summary: '删除客户内部 SKU',
description: '删除前检查是否有映射引用,有引用时禁止删除',
security: [['bearerAuth' => []]],
tags: ['SkuOrigins'],
parameters: [
new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(
response: 200,
description: '删除成功',
content: new OA\JsonContent(properties: [
new OA\Property(property: 'code', type: 'integer', example: 0),
new OA\Property(property: 'message', type: 'string', example: '删除成功'),
])
),
new OA\Response(response: 404, description: '数据不存在', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
new OA\Response(response: 409, description: '存在映射引用', content: new OA\JsonContent(ref: '#/components/schemas/ErrorResponse')),
]
)]
#[RequestMapping(path: "{id}", methods: "DELETE")]
public function destroy(int $id): ResponseInterface|array
{
$query = SkuOrigin::query();
$this->applyDataScope($query);
$record = $query->where('id', $id)->first();
if (!$record) {
return $this->response->json([
'code' => 404,
'message' => '数据不存在',
])->withStatus(404);
}
// 检查映射引用
if ($this->skuService->hasReferences($id)) {
return $this->response->json([
'code' => 409,
'message' => '该 SKU 存在映射引用,请先删除相关映射记录',
])->withStatus(409);
}
$sku_value = $record->sku;
$record->delete();
$user_id = OperationLogService::getCurrentUserId();
if ($user_id) {
OperationLogService::log(
$user_id,
'delete',
'sku_origin',
$id,
"删除内部 SKU: {$sku_value}",
ip: $this->request->getHeaderLine('x-real-ip') ?: null,
);
}
return [
'code' => 0,
'message' => '删除成功',
];
}
/**
* DataScope 过滤(基于 company_id
*/
private function applyDataScope(\Hyperf\Database\Model\Builder $query): void
{
$scope_type = $this->request->getAttribute('scope_type');
$scope_ids = $this->request->getAttribute('scope_ids', []);
if ($scope_type === 'store') {
$company_ids = \App\Model\Store::query()
->whereIn('id', $scope_ids)
->distinct()
->pluck('company_id')
->toArray();
$query->whereIn('company_id', $company_ids);
} elseif ($scope_type === 'platform') {
$company_ids = \App\Model\Store::query()
->whereIn('platform_id', $scope_ids)
->distinct()
->pluck('company_id')
->toArray();
$query->whereIn('company_id', $company_ids);
}
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\Database\Model\Relations\BelongsTo;
use Hyperf\DbConnection\Model\Model;
use OpenApi\Attributes as OA;
/**
* @property int $id 主键
* @property int $company_id 公司 ID
* @property int $platform_id 平台 ID
* @property string $platform_product_id 平台商品 ID
* @property string $origin_sku 客户侧匹配的 SKU 编码
* @property int|null $origin_sku_id 关联 skus_origin.id
* @property string|null $platform_outer_sku 平台侧使用的 SKU 编码
* @property string|null $generation_strategy 生成策略记录
* @property int|null $store_id 店铺 ID
* @property int|null $warehouse_id 仓库 ID
* @property boolean $enabled 是否启用
* @property string|null $note 备注
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
#[OA\Schema(
schema: 'SkuMapping',
description: 'SKU 平台映射',
properties: [
new OA\Property(property: 'id', type: 'integer', example: 1),
new OA\Property(property: 'company_id', type: 'integer', example: 3),
new OA\Property(property: 'platform_id', type: 'integer', example: 1),
new OA\Property(property: 'platform_product_id', type: 'string', example: 'ITEM-001'),
new OA\Property(property: 'origin_sku', type: 'string', example: '0032'),
new OA\Property(property: 'origin_sku_id', type: 'integer', nullable: true, example: 1),
new OA\Property(property: 'platform_outer_sku', type: 'string', nullable: true, example: 'C03_0032'),
new OA\Property(property: 'generation_strategy', type: 'string', nullable: true, example: 'prefix:C03'),
new OA\Property(property: 'store_id', type: 'integer', nullable: true, example: 101),
new OA\Property(property: 'warehouse_id', type: 'integer', nullable: true, example: 1),
new OA\Property(property: 'enabled', type: 'boolean', example: true),
new OA\Property(property: 'note', type: 'string', nullable: true, example: '用于 Shopee 马来站'),
new OA\Property(property: 'created_at', type: 'string', format: 'date-time'),
new OA\Property(property: 'updated_at', type: 'string', format: 'date-time'),
]
)]
class SkuMapping extends Model
{
/**
* The table associated with the model.
*/
protected ?string $table = 'skus_mapping';
/**
* The attributes that are mass assignable.
*/
protected array $fillable = [
'company_id',
'platform_id',
'platform_product_id',
'origin_sku',
'origin_sku_id',
'platform_outer_sku',
'generation_strategy',
'store_id',
'warehouse_id',
'enabled',
'note',
];
/**
* The attributes that should be cast to native types.
*/
protected array $casts = [
'id' => 'integer',
'company_id' => 'integer',
'platform_id' => 'integer',
'origin_sku_id' => 'integer',
'store_id' => 'integer',
'warehouse_id' => 'integer',
'enabled' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
public function company(): BelongsTo
{
return $this->belongsTo(Company::class, 'company_id');
}
public function platform(): BelongsTo
{
return $this->belongsTo(Platform::class, 'platform_id');
}
public function store(): BelongsTo
{
return $this->belongsTo(Store::class, 'store_id');
}
public function skuOrigin(): BelongsTo
{
return $this->belongsTo(SkuOrigin::class, 'origin_sku_id');
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\Database\Model\Relations\BelongsTo;
use Hyperf\Database\Model\Relations\HasMany;
use Hyperf\DbConnection\Model\Model;
use OpenApi\Attributes as OA;
/**
* @property int $id 主键
* @property int $company_id 公司 ID
* @property string $sku 客户侧提供的 SKU
* @property string|null $hs 海关商品分类编码
* @property string $barcode 条形码/GTIN
* @property string $name 产品名称(英文)
* @property string|null $label 产品名称(中文)
* @property string|null $ledger 账册与批次备注
* @property array|null $ext 扩展字段
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
#[OA\Schema(
schema: 'SkuOrigin',
description: '客户内部 SKU',
properties: [
new OA\Property(property: 'id', type: 'integer', example: 1),
new OA\Property(property: 'company_id', type: 'integer', example: 3),
new OA\Property(property: 'sku', type: 'string', example: '0032'),
new OA\Property(property: 'hs', type: 'string', nullable: true, example: '6403990090'),
new OA\Property(property: 'barcode', type: 'string', example: '6901234567890'),
new OA\Property(property: 'name', type: 'string', example: 'Running Shoes Model A'),
new OA\Property(property: 'label', type: 'string', nullable: true, example: '跑步鞋 A 款'),
new OA\Property(property: 'ledger', type: 'string', nullable: true, example: '批次 2026-Q1'),
new OA\Property(property: 'ext', type: 'object', nullable: true, description: '扩展字段'),
new OA\Property(property: 'created_at', type: 'string', format: 'date-time'),
new OA\Property(property: 'updated_at', type: 'string', format: 'date-time'),
]
)]
class SkuOrigin extends Model
{
/**
* The table associated with the model.
*/
protected ?string $table = 'skus_origin';
/**
* The attributes that are mass assignable.
*/
protected array $fillable = [
'company_id',
'sku',
'hs',
'barcode',
'name',
'label',
'ledger',
'ext',
];
/**
* The attributes that should be cast to native types.
*/
protected array $casts = [
'id' => 'integer',
'company_id' => 'integer',
'ext' => 'json',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
public function company(): BelongsTo
{
return $this->belongsTo(Company::class, 'company_id');
}
public function mappings(): HasMany
{
return $this->hasMany(SkuMapping::class, 'origin_sku_id');
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\SkuMapping;
use App\Model\SkuOrigin;
use Hyperf\Stringable\Str;
/**
* SKU 业务逻辑服务
*
* 负责 platform_outer_sku 的自动生成、重复检测等业务逻辑
*/
class SkuService
{
/**
* 生成 platform_outer_sku
*
* @param string $strategy 生成策略:prefix | prefix_random | manual
* @param string $origin_sku 原始 SKU 编码
* @param string $prefix 前缀
* @param int $random_length 随机部分长度(仅 prefix_random 模式)
* @param string|null $manual_value 手动输入值(仅 manual 模式)
* @return string 生成的 platform_outer_sku
*/
public function generatePlatformOuterSku(
string $strategy,
string $origin_sku,
string $prefix = '',
int $random_length = 4,
?string $manual_value = null,
): string {
return match ($strategy) {
'prefix' => $this->generatePrefixSku($prefix, $origin_sku),
'prefix_random' => $this->generatePrefixRandomSku($prefix, $random_length),
'manual' => $manual_value ?? '',
default => throw new \InvalidArgumentException("不支持的生成策略: {$strategy}"),
};
}
/**
* 前缀模式:{prefix}_{origin_sku}
*/
private function generatePrefixSku(string $prefix, string $origin_sku): string
{
if ($prefix === '') {
return $origin_sku;
}
return "{$prefix}_{$origin_sku}";
}
/**
* 前缀+随机模式:{prefix}_{random_string}
*/
private function generatePrefixRandomSku(string $prefix, int $random_length): string
{
$random_part = Str::upper(Str::random($random_length));
if ($prefix === '') {
return $random_part;
}
return "{$prefix}_{$random_part}";
}
/**
* 构建生成策略记录字符串
*/
public function buildStrategyRecord(string $strategy, string $prefix = '', int $random_length = 4): string
{
return match ($strategy) {
'prefix' => "prefix:{$prefix}",
'prefix_random' => "prefix_random:{$prefix}:{$random_length}",
'manual' => 'manual',
default => $strategy,
};
}
/**
* 检查某个 origin_sku 在指定平台下是否已存在映射记录
*
* @return array{has_duplicate: bool, existing_mappings: array, message: string}
*/
public function checkDuplicate(int $origin_sku_id, int $platform_id): array
{
$existing = SkuMapping::query()
->where('origin_sku_id', $origin_sku_id)
->where('platform_id', $platform_id)
->where('enabled', true)
->get(['id', 'store_id', 'platform_outer_sku', 'note']);
$has_duplicate = $existing->isNotEmpty();
$message = $has_duplicate
? "该 origin_sku 在当前平台下已有 {$existing->count()} 条映射记录,可直接复用已有的 platform_outer_sku"
: '';
return [
'has_duplicate' => $has_duplicate,
'existing_mappings' => $existing->toArray(),
'message' => $message,
];
}
/**
* 检查 origin_sku 是否有映射引用(用于删除前检查)
*/
public function hasReferences(int $origin_sku_id): bool
{
return SkuMapping::query()
->where('origin_sku_id', $origin_sku_id)
->exists();
}
/**
* 检查 platform_outer_sku 在指定平台内是否唯一
*/
public function isPlatformOuterSkuUnique(string $platform_outer_sku, int $platform_id, ?int $exclude_id = null): bool
{
$query = SkuMapping::query()
->where('platform_outer_sku', $platform_outer_sku)
->where('platform_id', $platform_id);
if ($exclude_id !== null) {
$query->where('id', '!=', $exclude_id);
}
return !$query->exists();
}
}