- simulateBom API 엔드포인트 추가 (calculateBomWithDebug 연동) - simulator.blade.php: BOM 디버깅 모드 탭 추가 - 10단계 디버그 스텝 패널 - 공정별 품목 그룹화 표시 - 원가 요약 (공정별 소계, 총합계) - FormulaEvaluatorService: currentTenantId 속성 추가 - 콘솔/API에서 tenant_id 전달 가능하도록 수정 - routes/api.php: simulate-bom 라우트 추가
426 lines
12 KiB
PHP
426 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\Admin\Quote;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\Quote\StoreQuoteFormulaRequest;
|
|
use App\Http\Requests\Quote\UpdateQuoteFormulaRequest;
|
|
use App\Services\Quote\FormulaEvaluatorService;
|
|
use App\Services\Quote\QuoteFormulaService;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\View\View;
|
|
|
|
class QuoteFormulaController extends Controller
|
|
{
|
|
public function __construct(
|
|
private readonly QuoteFormulaService $formulaService,
|
|
private readonly FormulaEvaluatorService $evaluatorService
|
|
) {}
|
|
|
|
/**
|
|
* 수식 목록 (HTMX용)
|
|
*/
|
|
public function index(Request $request): View|JsonResponse
|
|
{
|
|
$filters = $request->only(['search', 'category_id', 'type', 'is_active', 'trashed', 'sort_by', 'sort_direction']);
|
|
$formulas = $this->formulaService->getFormulas($filters, 15);
|
|
|
|
// HTMX 요청이면 HTML 파셜 반환
|
|
if ($request->header('HX-Request')) {
|
|
return view('quote-formulas.partials.table', compact('formulas'));
|
|
}
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'data' => $formulas,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 통계
|
|
*/
|
|
public function stats(): JsonResponse
|
|
{
|
|
$stats = $this->formulaService->getFormulaStats();
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'data' => $stats,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 상세 조회
|
|
*/
|
|
public function show(int $id): JsonResponse
|
|
{
|
|
$formula = $this->formulaService->getFormulaById($id, true);
|
|
|
|
if (! $formula) {
|
|
return response()->json([
|
|
'success' => false,
|
|
'message' => '수식을 찾을 수 없습니다.',
|
|
], 404);
|
|
}
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'data' => $formula,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 생성
|
|
*/
|
|
public function store(StoreQuoteFormulaRequest $request): JsonResponse
|
|
{
|
|
$validated = $request->validated();
|
|
|
|
// 변수명 중복 체크
|
|
if ($this->formulaService->isVariableExists($validated['variable'])) {
|
|
return response()->json([
|
|
'success' => false,
|
|
'message' => '이미 사용 중인 변수명입니다.',
|
|
], 422);
|
|
}
|
|
|
|
$formula = $this->formulaService->createFormula($validated);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => '수식이 생성되었습니다.',
|
|
'data' => $formula,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 수정
|
|
*/
|
|
public function update(UpdateQuoteFormulaRequest $request, int $id): JsonResponse
|
|
{
|
|
$validated = $request->validated();
|
|
|
|
// 변수명 중복 체크 (자신 제외)
|
|
if (isset($validated['variable']) && $this->formulaService->isVariableExists($validated['variable'], $id)) {
|
|
return response()->json([
|
|
'success' => false,
|
|
'message' => '이미 사용 중인 변수명입니다.',
|
|
], 422);
|
|
}
|
|
|
|
$this->formulaService->updateFormula($id, $validated);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => '수식이 수정되었습니다.',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 삭제 (Soft Delete)
|
|
*/
|
|
public function destroy(int $id): JsonResponse
|
|
{
|
|
$this->formulaService->deleteFormula($id);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => '수식이 삭제되었습니다.',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 복원
|
|
*/
|
|
public function restore(int $id): JsonResponse
|
|
{
|
|
$this->formulaService->restoreFormula($id);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => '수식이 복원되었습니다.',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 영구 삭제
|
|
*/
|
|
public function forceDestroy(int $id): JsonResponse
|
|
{
|
|
$this->formulaService->forceDeleteFormula($id);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => '수식이 영구 삭제되었습니다.',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 활성/비활성 토글
|
|
*/
|
|
public function toggleActive(int $id): JsonResponse
|
|
{
|
|
$formula = $this->formulaService->toggleActive($id);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => $formula->is_active ? '수식이 활성화되었습니다.' : '수식이 비활성화되었습니다.',
|
|
'data' => ['is_active' => $formula->is_active],
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 카테고리별 수식 목록 (실행 순서)
|
|
*/
|
|
public function byCategory(int $categoryId): JsonResponse
|
|
{
|
|
$formulas = $this->formulaService->getFormulasByCategory($categoryId);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'data' => $formulas,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 순서 변경
|
|
*/
|
|
public function reorder(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'formula_ids' => 'required|array',
|
|
'formula_ids.*' => 'integer|exists:quote_formulas,id',
|
|
]);
|
|
|
|
$this->formulaService->reorder($validated['formula_ids']);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => '순서가 변경되었습니다.',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 사용 가능한 변수 목록
|
|
*/
|
|
public function variables(): JsonResponse
|
|
{
|
|
$variables = $this->formulaService->getAvailableVariables();
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'data' => $variables,
|
|
]);
|
|
}
|
|
|
|
// =========================================================================
|
|
// 수식 검증 및 테스트 API
|
|
// =========================================================================
|
|
|
|
/**
|
|
* 수식 문법 검증
|
|
*/
|
|
public function validate(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'formula' => 'required|string|max:2000',
|
|
]);
|
|
|
|
$result = $this->evaluatorService->validateFormula($validated['formula']);
|
|
|
|
return response()->json([
|
|
'success' => $result['success'],
|
|
'data' => $result,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 단일 수식 테스트 실행
|
|
*/
|
|
public function test(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'formula' => 'required|string|max:2000',
|
|
'variables' => 'nullable|array',
|
|
]);
|
|
|
|
$this->evaluatorService->resetVariables();
|
|
|
|
$result = $this->evaluatorService->evaluate(
|
|
$validated['formula'],
|
|
$validated['variables'] ?? []
|
|
);
|
|
|
|
$errors = $this->evaluatorService->getErrors();
|
|
|
|
return response()->json([
|
|
'success' => empty($errors),
|
|
'data' => [
|
|
'result' => $result,
|
|
'errors' => $errors,
|
|
],
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 전체 수식 시뮬레이션
|
|
*/
|
|
public function simulate(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'category_id' => 'nullable|integer|exists:quote_formula_categories,id',
|
|
'input_variables' => 'required|array',
|
|
]);
|
|
|
|
// 카테고리별 수식 조회
|
|
$categoryId = $validated['category_id'] ?? null;
|
|
$formulas = $categoryId
|
|
? $this->formulaService->getFormulasByCategory($categoryId)
|
|
: $this->formulaService->getAllActiveFormulas();
|
|
|
|
// 카테고리별로 그룹핑
|
|
$formulasByCategory = $formulas->groupBy(fn ($f) => $f->category->code);
|
|
|
|
// 전체 실행
|
|
$this->evaluatorService->resetVariables();
|
|
$result = $this->evaluatorService->executeAll(
|
|
$formulasByCategory,
|
|
$validated['input_variables']
|
|
);
|
|
|
|
// 품목 상세 정보 및 BOM 트리 추가
|
|
if (! empty($result['items'])) {
|
|
$result['items'] = $this->evaluatorService->enrichItemsWithDetails($result['items']);
|
|
}
|
|
|
|
// 오류가 있어도 계산된 결과는 반환 (부분 성공)
|
|
// 오류는 data.errors에 포함되어 UI에서 별도 표시
|
|
return response()->json([
|
|
'success' => true,
|
|
'data' => $result,
|
|
'has_errors' => ! empty($result['errors']),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 수식 복제
|
|
*/
|
|
public function duplicate(int $id): JsonResponse
|
|
{
|
|
$formula = $this->formulaService->duplicateFormula($id);
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => '수식이 복제되었습니다.',
|
|
'data' => $formula,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* BOM 기반 시뮬레이션 (디버깅 포함)
|
|
*
|
|
* Design 시뮬레이터와 동일한 계산 로직을 사용하여
|
|
* 10단계 디버깅 정보, 공정별 그룹화, 카테고리 가격 계산을 포함합니다.
|
|
*/
|
|
public function simulateBom(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'finished_goods_code' => 'required|string|max:50',
|
|
'input_variables' => 'required|array',
|
|
'input_variables.W0' => 'required|numeric|min:1',
|
|
'input_variables.H0' => 'required|numeric|min:1',
|
|
]);
|
|
|
|
$tenantId = session('selected_tenant_id');
|
|
|
|
if (! $tenantId) {
|
|
return response()->json([
|
|
'success' => false,
|
|
'message' => '테넌트를 선택해주세요.',
|
|
], 400);
|
|
}
|
|
|
|
// 디버그 모드 활성화
|
|
$this->evaluatorService->enableDebugMode();
|
|
|
|
// BOM 기반 계산 (10단계 디버깅 포함)
|
|
$result = $this->evaluatorService->calculateBomWithDebug(
|
|
$validated['finished_goods_code'],
|
|
$validated['input_variables'],
|
|
$tenantId
|
|
);
|
|
|
|
return response()->json([
|
|
'success' => $result['success'] ?? false,
|
|
'data' => $result,
|
|
'message' => $result['error'] ?? null,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 전체 품목 목록 (시뮬레이터용)
|
|
*/
|
|
public function items(Request $request): JsonResponse
|
|
{
|
|
$tenantId = session('selected_tenant_id');
|
|
|
|
if (! $tenantId) {
|
|
return response()->json([
|
|
'success' => false,
|
|
'message' => '테넌트를 선택해주세요.',
|
|
], 400);
|
|
}
|
|
|
|
$query = \DB::table('items')
|
|
->where('tenant_id', $tenantId)
|
|
->whereNull('deleted_at')
|
|
->where('is_active', true);
|
|
|
|
// 검색
|
|
if ($search = $request->get('search')) {
|
|
$query->where(function ($q) use ($search) {
|
|
$q->where('code', 'like', "%{$search}%")
|
|
->orWhere('name', 'like', "%{$search}%");
|
|
});
|
|
}
|
|
|
|
// 품목 유형 필터
|
|
if ($itemType = $request->get('item_type')) {
|
|
$query->where('item_type', $itemType);
|
|
}
|
|
|
|
$items = $query->orderBy('item_type')
|
|
->orderBy('code')
|
|
->get(['id', 'code', 'name', 'item_type', 'unit', 'bom']);
|
|
|
|
// BOM 정보 가공
|
|
$items = $items->map(function ($item) {
|
|
$bomData = json_decode($item->bom ?? '[]', true);
|
|
|
|
return [
|
|
'id' => $item->id,
|
|
'code' => $item->code,
|
|
'name' => $item->name,
|
|
'item_type' => $item->item_type,
|
|
'item_type_label' => $this->evaluatorService->getItemTypeLabel($item->item_type),
|
|
'unit' => $item->unit,
|
|
'has_bom' => ! empty($bomData),
|
|
'bom_count' => count($bomData),
|
|
];
|
|
});
|
|
|
|
// 품목 유형별 통계
|
|
$stats = $items->groupBy('item_type')->map(fn ($group) => $group->count());
|
|
|
|
return response()->json([
|
|
'success' => true,
|
|
'data' => [
|
|
'items' => $items->values(),
|
|
'stats' => $stats,
|
|
'total' => $items->count(),
|
|
],
|
|
]);
|
|
}
|
|
}
|