Files
sam-api/app/Services/ProductBomService.php

336 lines
13 KiB
PHP

<?php
namespace App\Services;
use App\Models\Materials\Material;
use App\Models\Products\Product;
use App\Models\Products\ProductComponent;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ProductBomService extends Service
{
/**
* 목록: 제품/자재를 통합 반환
* - 반환 형태 예:
* [
* { "id": 10, "ref_type": "PRODUCT", "ref_id": 3, "code": "P-003", "name": "모듈A", "quantity": "2.0000", "sort_order": 1, "is_default": 1 },
* { "id": 11, "ref_type": "MATERIAL", "ref_id": 5, "code": "M-005", "name": "알루미늄판", "unit":"EA", "quantity": "4.0000", "sort_order": 2 }
* ]
*/
public function index(int $parentProductId, array $params)
{
$tenantId = $this->tenantId();
// 부모 제품 유효성
$this->assertProduct($tenantId, $parentProductId);
$items = ProductComponent::query()
->where('tenant_id', $tenantId)
->where('parent_product_id', $parentProductId)
->orderBy('sort_order')
->get();
// 리졸브(제품/자재)
$productIds = $items->where('ref_type', 'PRODUCT')->pluck('child_product_id')->filter()->unique()->values();
$materialIds = $items->where('ref_type', 'MATERIAL')->pluck('material_id')->filter()->unique()->values();
$products = $productIds->isNotEmpty()
? Product::query()->where('tenant_id', $tenantId)->whereIn('id', $productIds)->get(['id','code','name','product_type','category_id'])->keyBy('id')
: collect();
$materials = $materialIds->isNotEmpty()
? Material::query()->where('tenant_id', $tenantId)->whereIn('id', $materialIds)->get(['id','material_code as code','name','unit','category_id'])->keyBy('id')
: collect();
return $items->map(function ($row) use ($products, $materials) {
$base = [
'id' => (int)$row->id,
'ref_type' => $row->ref_type,
'quantity' => $row->quantity,
'sort_order' => (int)$row->sort_order,
'is_default' => (int)$row->is_default,
];
if ($row->ref_type === 'PRODUCT') {
$p = $products->get($row->child_product_id);
return $base + [
'ref_id' => (int)$row->child_product_id,
'code' => $p?->code,
'name' => $p?->name,
'product_type' => $p?->product_type,
'category_id' => $p?->category_id,
];
} else { // MATERIAL
$m = $materials->get($row->material_id);
return $base + [
'ref_id' => (int)$row->material_id,
'code' => $m?->code,
'name' => $m?->name,
'unit' => $m?->unit,
'category_id' => $m?->category_id,
];
}
})->values();
}
/**
* 일괄 업서트
* items[]: { id?, ref_type: PRODUCT|MATERIAL, ref_id: int, quantity: number, sort_order?: int, is_default?: 0|1 }
*/
public function bulkUpsert(int $parentProductId, array $items): array
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
$this->assertProduct($tenantId, $parentProductId);
if (!is_array($items) || empty($items)) {
throw new BadRequestHttpException(__('error.empty_items'));
}
$created = 0; $updated = 0;
DB::transaction(function () use ($tenantId, $userId, $parentProductId, $items, &$created, &$updated) {
foreach ($items as $it) {
$payload = $this->validateItem($it);
// ref 확인 & 자기참조 방지
$this->assertReference($tenantId, $parentProductId, $payload['ref_type'], (int)$payload['ref_id']);
if (!empty($it['id'])) {
$pc = ProductComponent::query()
->where('tenant_id', $tenantId)
->where('parent_product_id', $parentProductId)
->find((int)$it['id']);
if (!$pc) throw new BadRequestHttpException(__('error.not_found'));
// ref 변경 허용 시: 충돌 검사
[$childProductId, $materialId] = $this->splitRef($payload);
$pc->update([
'ref_type' => $payload['ref_type'],
'child_product_id' => $childProductId,
'material_id' => $materialId,
'quantity' => $payload['quantity'],
'sort_order' => $payload['sort_order'] ?? $pc->sort_order,
'is_default' => $payload['is_default'] ?? $pc->is_default,
'updated_by' => $userId,
]);
$updated++;
} else {
// 신규
[$childProductId, $materialId] = $this->splitRef($payload);
ProductComponent::create([
'tenant_id' => $tenantId,
'parent_product_id' => $parentProductId,
'ref_type' => $payload['ref_type'],
'child_product_id' => $childProductId,
'material_id' => $materialId,
'quantity' => $payload['quantity'],
'sort_order' => $payload['sort_order'] ?? 0,
'is_default' => $payload['is_default'] ?? 0,
'created_by' => $userId,
]);
$created++;
}
}
});
return compact('created', 'updated');
}
// 단건 수정
public function update(int $parentProductId, int $itemId, array $data)
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
$this->assertProduct($tenantId, $parentProductId);
$pc = ProductComponent::query()
->where('tenant_id', $tenantId)
->where('parent_product_id', $parentProductId)
->find($itemId);
if (!$pc) throw new BadRequestHttpException(__('error.not_found'));
$v = Validator::make($data, [
'ref_type' => 'sometimes|in:PRODUCT,MATERIAL',
'ref_id' => 'sometimes|integer',
'quantity' => 'sometimes|numeric|min:0.0001',
'sort_order' => 'sometimes|integer|min:0',
'is_default' => 'sometimes|in:0,1',
]);
$payload = $v->validate();
if (isset($payload['ref_type']) || isset($payload['ref_id'])) {
$refType = $payload['ref_type'] ?? $pc->ref_type;
$refId = isset($payload['ref_id'])
? (int)$payload['ref_id']
: ($pc->ref_type === 'PRODUCT' ? (int)$pc->child_product_id : (int)$pc->material_id);
$this->assertReference($tenantId, $parentProductId, $refType, $refId);
[$childProductId, $materialId] = $this->splitRef(['ref_type' => $refType, 'ref_id' => $refId]);
$pc->ref_type = $refType;
$pc->child_product_id = $childProductId;
$pc->material_id = $materialId;
}
if (isset($payload['quantity'])) $pc->quantity = $payload['quantity'];
if (isset($payload['sort_order'])) $pc->sort_order = $payload['sort_order'];
if (isset($payload['is_default'])) $pc->is_default = $payload['is_default'];
$pc->updated_by = $userId;
$pc->save();
return $pc->refresh();
}
// 삭제
public function destroy(int $parentProductId, int $itemId): void
{
$tenantId = $this->tenantId();
$this->assertProduct($tenantId, $parentProductId);
$pc = ProductComponent::query()
->where('tenant_id', $tenantId)
->where('parent_product_id', $parentProductId)
->find($itemId);
if (!$pc) throw new BadRequestHttpException(__('error.not_found'));
$pc->delete();
}
// 정렬 변경
public function reorder(int $parentProductId, array $items): void
{
$tenantId = $this->tenantId();
$this->assertProduct($tenantId, $parentProductId);
if (!is_array($items)) throw new BadRequestHttpException(__('error.invalid_payload'));
DB::transaction(function () use ($tenantId, $parentProductId, $items) {
foreach ($items as $row) {
if (!isset($row['id'], $row['sort_order'])) continue;
ProductComponent::query()
->where('tenant_id', $tenantId)
->where('parent_product_id', $parentProductId)
->where('id', (int)$row['id'])
->update(['sort_order' => (int)$row['sort_order']]);
}
});
}
// 요약(간단 합계/건수)
public function summary(int $parentProductId): array
{
$tenantId = $this->tenantId();
$this->assertProduct($tenantId, $parentProductId);
$items = ProductComponent::query()
->where('tenant_id', $tenantId)
->where('parent_product_id', $parentProductId)
->get();
$cnt = $items->count();
$cntP = $items->where('ref_type','PRODUCT')->count();
$cntM = $items->where('ref_type','MATERIAL')->count();
$qtySum = (string)$items->sum('quantity');
return [
'count' => $cnt,
'count_product' => $cntP,
'count_material'=> $cntM,
'quantity_sum' => $qtySum,
];
}
// 유효성 검사(중복/자기참조/음수 등)
public function validateBom(int $parentProductId): array
{
$tenantId = $this->tenantId();
$this->assertProduct($tenantId, $parentProductId);
$items = ProductComponent::query()
->where('tenant_id', $tenantId)
->where('parent_product_id', $parentProductId)
->orderBy('sort_order')
->get();
$errors = [];
$seen = [];
foreach ($items as $row) {
if ($row->quantity <= 0) {
$errors[] = ['id' => $row->id, 'error' => 'INVALID_QUANTITY'];
}
$key = $row->ref_type . ':' . ($row->ref_type === 'PRODUCT' ? $row->child_product_id : $row->material_id);
if (isset($seen[$key])) {
$errors[] = ['id' => $row->id, 'error' => 'DUPLICATE_ITEM'];
} else {
$seen[$key] = true;
}
// 자기참조
if ($row->ref_type === 'PRODUCT' && (int)$row->child_product_id === (int)$parentProductId) {
$errors[] = ['id' => $row->id, 'error' => 'SELF_REFERENCE'];
}
}
return [
'valid' => count($errors) === 0,
'errors' => $errors,
];
}
// ---------- helpers ----------
private function validateItem(array $it): array
{
$v = Validator::make($it, [
'id' => 'nullable|integer',
'ref_type' => 'required|in:PRODUCT,MATERIAL',
'ref_id' => 'required|integer',
'quantity' => 'required|numeric|min:0.0001',
'sort_order' => 'nullable|integer|min:0',
'is_default' => 'nullable|in:0,1',
]);
return $v->validate();
}
private function splitRef(array $payload): array
{
// returns [child_product_id, material_id]
if ($payload['ref_type'] === 'PRODUCT') {
return [(int)$payload['ref_id'], null];
}
return [null, (int)$payload['ref_id']];
}
private function assertProduct(int $tenantId, int $productId): void
{
$exists = Product::query()->where('tenant_id', $tenantId)->where('id', $productId)->exists();
if (!$exists) {
// ko: 제품 정보를 찾을 수 없습니다.
throw new NotFoundHttpException(__('error.not_found_resource', ['resource' => '제품']));
}
}
private function assertReference(int $tenantId, int $parentProductId, string $refType, int $refId): void
{
if ($refType === 'PRODUCT') {
if ($refId === $parentProductId) {
throw new BadRequestHttpException(__('error.invalid_payload')); // 자기참조 방지
}
$ok = Product::query()->where('tenant_id', $tenantId)->where('id', $refId)->exists();
if (!$ok) throw new BadRequestHttpException(__('error.not_found'));
} else {
$ok = Material::query()->where('tenant_id', $tenantId)->where('id', $refId)->exists();
if (!$ok) throw new BadRequestHttpException(__('error.not_found'));
}
}
}