[feat] negodata: 타결 상한(done_ceiling) — 세팅 기본율%·견적 override·세션 박제, 견적생성 3단계 타결/낙찰 섹션 분리·재생성 상속

This commit is contained in:
minaChoi committed 2026-08-04 08:56:03 +09:00
1 parent 2bf91d64f5
commit 91b8dc77a0
37 files changed
+962 -131

No files matched your search

@@ -113,6 +113,7 @@ export * from './quotationData';
export * from './quotationDataCloseReason';
export * from './quotationDataCreatedAt';
export * from './quotationDataCreatorName';
export * from './quotationDataDoneCeilingRate';
export * from './quotationDataEqualBidData';
export * from './quotationDataEqualBidYn';
export * from './quotationDataItemId';
@@ -176,6 +177,7 @@ export * from './reqCreateItemSellingPrice';
export * from './reqCreateItemSpec';
export * from './reqCreateItemVatYn';
export * from './reqCreateQuotation';
export * from './reqCreateQuotationDoneCeilingRate';
export * from './reqCreateQuotationManagerContactNumber';
export * from './reqCreateQuotationManagerEmail';
export * from './reqCreateQuotationManagerName';
@@ -198,6 +200,10 @@ export * from './reqCreateSupplierManagerName';
export * from './reqCreateSupplierTotalRevenue';
export * from './reqLogin';
export * from './reqRegenerateQuotation';
export * from './reqRegenerateQuotationCardIds';
export * from './reqRegenerateQuotationDoneCeilingRate';
export * from './reqRegenerateQuotationEndTime';
export * from './reqRegenerateQuotationTargetPrice';
export * from './reqRejectRenegotiation';
export * from './reqResetSupplierAccountPassword';
export * from './reqResetSupplierAccountPasswordPassword';
@@ -248,6 +254,7 @@ export * from './reqUpdateMeName';
export * from './reqUpdateMePassword';
export * from './reqUpdateQuotationSetting';
export * from './reqUpdateQuotationSettingCardCount';
export * from './reqUpdateQuotationSettingDoneCeilingRate';
export * from './reqUpdateQuotationSettingTargetMarginRate';
export * from './reqUpdateSupplier';
export * from './reqUpdateSupplierAccountStatus';
@@ -19,6 +19,7 @@ import type { QuotationDataEqualBidData } from './quotationDataEqualBidData';
import type { QuotationDataCloseReason } from './quotationDataCloseReason';
import type { QuotationDataMidAction } from './quotationDataMidAction';
import type { QuotationDataOverAction } from './quotationDataOverAction';
import type { QuotationDataDoneCeilingRate } from './quotationDataDoneCeilingRate';
import type { QuotationDataItemId } from './quotationDataItemId';
import type { QuotationDataItemName } from './quotationDataItemName';
import type { QuotationDataCreatorName } from './quotationDataCreatorName';
@@ -51,6 +52,7 @@ export interface QuotationData {
close_reason?: QuotationDataCloseReason;
mid_action?: QuotationDataMidAction;
over_action?: QuotationDataOverAction;
done_ceiling_rate?: QuotationDataDoneCeilingRate;
participation_count?: number;
item_id?: QuotationDataItemId;
item_name?: QuotationDataItemName;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type QuotationDataDoneCeilingRate = number | null;
@@ -13,6 +13,7 @@ export interface QuotationSettingData {
user_id?: QuotationSettingDataUserId;
target_margin_rate: number;
card_count: number;
done_ceiling_rate: number;
created_at?: QuotationSettingDataCreatedAt;
updated_at?: QuotationSettingDataUpdatedAt;
}
@@ -13,6 +13,7 @@ import type { ReqCreateQuotationMemo } from './reqCreateQuotationMemo';
import type { ReqCreateQuotationMdPrice } from './reqCreateQuotationMdPrice';
import type { ReqCreateQuotationMidAction } from './reqCreateQuotationMidAction';
import type { ReqCreateQuotationOverAction } from './reqCreateQuotationOverAction';
import type { ReqCreateQuotationDoneCeilingRate } from './reqCreateQuotationDoneCeilingRate';
export interface ReqCreateQuotation {
qt_setting_id: string;
@@ -33,4 +34,5 @@ export interface ReqCreateQuotation {
card_ids?: string[];
mid_action?: ReqCreateQuotationMidAction;
over_action?: ReqCreateQuotationOverAction;
done_ceiling_rate?: ReqCreateQuotationDoneCeilingRate;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ReqCreateQuotationDoneCeilingRate = number | null;
@@ -8,4 +8,5 @@
export interface ReqCreateQuotationSetting {
target_margin_rate: number;
card_count?: number;
done_ceiling_rate?: number;
}
@@ -4,7 +4,15 @@
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { ReqRegenerateQuotationCardIds } from './reqRegenerateQuotationCardIds';
import type { ReqRegenerateQuotationTargetPrice } from './reqRegenerateQuotationTargetPrice';
import type { ReqRegenerateQuotationEndTime } from './reqRegenerateQuotationEndTime';
import type { ReqRegenerateQuotationDoneCeilingRate } from './reqRegenerateQuotationDoneCeilingRate';
export interface ReqRegenerateQuotation {
supplier_ids?: string[];
card_ids?: ReqRegenerateQuotationCardIds;
target_price?: ReqRegenerateQuotationTargetPrice;
end_time?: ReqRegenerateQuotationEndTime;
done_ceiling_rate?: ReqRegenerateQuotationDoneCeilingRate;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ReqRegenerateQuotationCardIds = string[] | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ReqRegenerateQuotationDoneCeilingRate = number | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ReqRegenerateQuotationEndTime = string | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ReqRegenerateQuotationTargetPrice = number | null;
@@ -6,8 +6,10 @@
*/
import type { ReqUpdateQuotationSettingTargetMarginRate } from './reqUpdateQuotationSettingTargetMarginRate';
import type { ReqUpdateQuotationSettingCardCount } from './reqUpdateQuotationSettingCardCount';
import type { ReqUpdateQuotationSettingDoneCeilingRate } from './reqUpdateQuotationSettingDoneCeilingRate';
export interface ReqUpdateQuotationSetting {
target_margin_rate?: ReqUpdateQuotationSettingTargetMarginRate;
card_count?: ReqUpdateQuotationSettingCardCount;
done_ceiling_rate?: ReqUpdateQuotationSettingDoneCeilingRate;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ReqUpdateQuotationSettingDoneCeilingRate = number | null;
@@ -12,6 +12,7 @@ import { Typography, typographyVariants } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
import { useScrollLock } from '@/lib/useScrollLock';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Combobox, type ComboOption } from '@/components/ui/combobox';
import type { Product, Partner, QuotationSetting, NegotiationCard } from '../types';
@@ -68,6 +69,8 @@ export function QuotationCreateModal({
const [mdPrice, setMdPrice] = useState(''); // MD 제시가(원). 비우면 미전송 → 서버가 상품값으로 목표가 산정
const [midAction, setMidAction] = useState<number>(DEFAULT_MID_ACTION); // 앵커~목표가 구간: 낙찰/개찰 (1:1 전용)
const [overAction, setOverAction] = useState<number>(DEFAULT_OVER_ACTION); // 목표가 초과 구간: 낙찰/개찰 (1:1 전용)
const [ceilingPct, setCeilingPct] = useState(''); // 협상 완료 상한율(%) 이 견적 override. 비우면 세팅 기본값
const [ceilingTouched, setCeilingTouched] = useState(false); // 상한율을 직접 건드렸는지 — 안 건드렸으면 세팅값 표시
const [submitting, setSubmitting] = useState(false);
const [mdTouched, setMdTouched] = useState(false); // 담당자가 제시가를 직접 건드렸는지 — 안 건드렸으면 자동 산출값을 채운다
// 매입가 네고율 차감 — 이 견적에서만 조정. 안 건드리면 세팅 기본값을 따른다(negoTouched=false). 네고율 값 자체는 세팅값 고정.
@@ -164,6 +167,8 @@ export function QuotationCreateModal({
targetLimitExceeded,
estimatedTargetPrice,
submitMdPrice,
settingCeilingRate,
doneCeilingPrice,
} = useTargetPrice({
quotationSettings,
settingId,
@@ -178,6 +183,7 @@ export function QuotationCreateModal({
negoTouched,
applyNego,
selectedCandidateKey,
doneCeilingRateOverride: ceilingTouched && ceilingPct !== '' ? Math.round(Number(ceilingPct) * 10) : null,
});
// ── 카드 선택 게이팅 — 부적합 카드 disabled·자동 선택/해제(useCardGating 이 소유) ──
@@ -268,6 +274,8 @@ export function QuotationCreateModal({
mdPrice: submitMdPrice,
midAction: oneToOne ? midAction : undefined,
overAction: oneToOne ? overAction : undefined,
// 완료 상한율 override — 직접 건드렸을 때만 전송(‰). 비우면 서버가 세팅 기본값 사용.
doneCeilingRate: ceilingTouched && ceilingPct !== '' ? Math.round(Number(ceilingPct) * 10) : undefined,
});
if (ok) onClose();
} finally {
@@ -428,7 +436,7 @@ export function QuotationCreateModal({
{(value) => {
const qs = quotationSettings.find((s) => s.qt_setting_id === value);
return qs
? `[${label('target_margin')}: ${qs.target_margin}] 카드 ${qs.card_use_count}`
? `[${label('target_margin')}: ${qs.target_margin}] 카드 ${qs.card_use_count} · 타결상한 +${qs.done_ceiling_rate / 10}%`
: '';
}}
</SelectValue>
@@ -436,46 +444,27 @@ export function QuotationCreateModal({
<SelectContent>
{quotationSettings.map((qs) => (
<SelectItem key={qs.qt_setting_id} value={qs.qt_setting_id}>
[{label('target_margin')}: {qs.target_margin}] 카드 {qs.card_use_count}
[{label('target_margin')}: {qs.target_margin}] 카드 {qs.card_use_count} · 타결상한 +{qs.done_ceiling_rate / 10}%
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{oneToOne ? (
<>
{/* 낙찰 기준(1:1 전용) — 스펙트럼 = 선택. 낙찰선을 앵커/목표가 중 택1, 목표가 초과는 항상 개찰. */}
<AwardLinePicker
mid={midAction}
over={overAction}
// 단조성: 초과=낙찰이면 앵커~목표가도 낙찰, 앵커~목표가=개찰이면 초과도 개찰(혼합 조합 방지)
onMid={(v) => {
setMidAction(v);
if (v === PriceGateAction.OPEN) setOverAction(PriceGateAction.OPEN);
}}
onOver={(v) => {
setOverAction(v);
if (v === PriceGateAction.AWARD) setMidAction(PriceGateAction.AWARD);
}}
/>
</>
) : (
/* 경매(1:N) — 낙찰 기준·협상카드 없음. 최저가 자동 낙찰 안내만. */
<div className="rounded border border-border bg-muted/20 p-3 flex items-start gap-2.5">
<Gavel size={18} className="text-primary mt-0.5 shrink-0" />
<div>
<Typography as="span" variant="small" className="font-semibold block">최저가 자동 낙찰</Typography>
<Typography as="span" variant="small" className="text-muted-foreground text-[10px] leading-snug">
1:N 견적은 가장 낮은 투찰가가 자동 낙찰됩니다. 낙찰 기준·협상카드 설정이 없습니다.
</Typography>
{/* ── 타결 기준 (협상) — 봇이 어느 가격까지 합의하면 타결로 볼지 ── */}
<div className="rounded-lg border border-border overflow-hidden">
<div className="flex items-center gap-2 px-3 py-2.5 border-b border-border bg-muted/30">
<span className="grid place-items-center h-5 w-5 rounded-md bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400 shrink-0"><CheckCheck size={12} /></span>
<div className="min-w-0">
<Typography as="span" variant="small" className="font-bold block leading-tight">타결 기준 <span className="text-muted-foreground font-normal text-[10px]">· 협상</span></Typography>
<Typography as="span" variant="small" className="text-muted-foreground text-[10px] block leading-tight">봇이 어느 가격까지 합의하면 타결로 볼지 정합니다</Typography>
</div>
</div>
)}
<div className="p-3 space-y-4">
{/* 목표가 산정 후보 — 후보 택1로 목표가 결정(기본=최저). 매입가 후보 행의 체크박스로 네고율 차감 여부 조정. 숨김필드는 제외. */}
{productId && targetBreakdown.length > 0 && (
<div className="rounded border border-border bg-muted/20 p-3 space-y-2">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Typography as="span" variant="label">
목표가 산정 후보 <span className="text-muted-foreground font-normal">({isReType ? '재' : '신규'})</span>
@@ -579,6 +568,91 @@ export function QuotationCreateModal({
)}
</div>
{/* 타결 상한 — 목표가 초과 허용폭. 봇이 이 이하로 합의하면 타결, 초과하면 결렬. 비우면 세팅 기본율. */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Typography as="label" variant="label">타결 상한가</Typography>
{/* OFF=세팅 기본율 그대로 · ON=이 견적만 직접 지정 */}
<label className="flex items-center gap-1.5 cursor-pointer">
<Typography as="span" variant="small" className="text-[10px] text-muted-foreground">이 견적만 조정</Typography>
<Switch
checked={ceilingTouched}
onCheckedChange={(on) => {
setCeilingTouched(on);
if (on && ceilingPct === '') setCeilingPct(String(settingCeilingRate / 10)); // 켤 때 세팅값에서 출발
}}
/>
</label>
</div>
{ceilingTouched ? (
<div className="flex items-center gap-1.5">
<Typography as="span" variant="small" className="text-[11px] text-muted-foreground">목표가 +</Typography>
<Input
type="number"
step="0.5"
min={0}
className="h-8 w-20 text-xs text-right"
value={ceilingPct}
onChange={(e) => setCeilingPct(e.target.value)}
/>
<Typography as="span" variant="small" className="text-[11px] text-muted-foreground">%</Typography>
</div>
) : (
<Typography as="p" variant="small" className="text-[11px] text-muted-foreground">
세팅 기본 <span className="font-semibold text-foreground">목표가 +{settingCeilingRate / 10}%</span> 적용
</Typography>
)}
<Typography as="p" variant="small" className="text-[10px] text-muted-foreground leading-snug">
{doneCeilingPrice != null ? (
<>최종 합의가가 <span className="font-bold text-foreground">₩{doneCeilingPrice.toLocaleString()}</span> 이하면 타결, 초과하면 결렬.</>
) : '목표가가 정해지면 타결 상한가가 자동 계산됩니다.'}
</Typography>
</div>
</div>
</div>
{/* ── 낙찰 기준 (마감) — 타결된 투찰가로 누구를 낙찰시킬지 ── */}
<div className="rounded-lg border border-border overflow-hidden">
<div className="flex items-center gap-2 px-3 py-2.5 border-b border-border bg-muted/30">
<span className="grid place-items-center h-5 w-5 rounded-md bg-primary/10 text-primary shrink-0"><Gavel size={12} /></span>
<div className="min-w-0">
<Typography as="span" variant="small" className="font-bold block leading-tight">낙찰 기준 <span className="text-muted-foreground font-normal text-[10px]">· 마감</span></Typography>
<Typography as="span" variant="small" className="text-muted-foreground text-[10px] block leading-tight">타결된 투찰가로 마감 때 누구를 낙찰시킬지 정합니다</Typography>
</div>
</div>
<div className="p-3">
{oneToOne ? (
/* 스펙트럼 = 선택. 낙찰선을 앵커/목표가 중 택1, 목표가 초과는 항상 개찰. */
<AwardLinePicker
mid={midAction}
over={overAction}
// 단조성: 초과=낙찰이면 앵커~목표가도 낙찰, 앵커~목표가=개찰이면 초과도 개찰(혼합 조합 방지)
onMid={(v) => {
setMidAction(v);
if (v === PriceGateAction.OPEN) setOverAction(PriceGateAction.OPEN);
}}
onOver={(v) => {
setOverAction(v);
if (v === PriceGateAction.AWARD) setMidAction(PriceGateAction.AWARD);
}}
/>
) : (
/* 경매(1:N) — 최저가 자동 낙찰. */
<div className="flex items-start gap-2.5">
<Gavel size={16} className="text-primary mt-0.5 shrink-0" />
<div>
<Typography as="span" variant="small" className="font-semibold block">최저가 자동 낙찰</Typography>
<Typography as="span" variant="small" className="text-muted-foreground text-[10px] leading-snug">
1:N 견적은 가장 낮은 투찰가가 자동 낙찰됩니다. 별도 낙찰 기준 설정이 없습니다.
</Typography>
</div>
</div>
)}
</div>
</div>
<div className="space-y-1">
<Typography as="label" variant="label">협력사 안내 메모 (선택)</Typography>
<textarea
@@ -1,42 +1,163 @@
import { useState } from 'react';
import { X, RefreshCw, Loader2 } from 'lucide-react';
import { useState, type ReactNode } from 'react';
import { X, RefreshCw, Loader2, CheckCheck, Lightbulb } from 'lucide-react';
import { useScrollLock } from '@/lib/useScrollLock';
import { showToast } from '@/lib/notify';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Typography } from '@/components/ui/typography';
import { type Partner, sessionStatusLabel } from '../../types';
import { Combobox } from '@/components/ui/combobox';
import { useListCards } from '@/api/generated/card/card';
import { mapCardData } from '@/features/cards/types';
import type { QuotationData } from '@/api/generated/model/quotationData';
import { CloseReason } from '@/api/generated/model';
import { useCardGating } from '../../hooks/useCardGating';
import type { RegenerateInput } from '../../hooks/useQuotations';
import { SelectedCardTable } from '../QuotationFormParts';
import { kstLocalInputAfter, isFutureLocalInput } from '../quotationForm.utils';
import { type Partner, type SessionView, type NegotiationCard, sessionStatusLabel } from '../../types';
import { ResultSummaryBand } from './ResultSummaryBand';
// 마감 사유별로 이번 라운드에서 손볼 레버를 짚어준다(안내만 — 선택값은 바꾸지 않는다).
const REGEN_HINT: Record<CloseReason, string> = {
[CloseReason.AWARDED]: '낙찰로 마감된 건입니다 — 같은 조건으로 한 라운드 더 열면 직전 낙찰과 중복될 수 있습니다.',
[CloseReason.OPEN_PRICE]: '목표가를 넘겨 개찰됐습니다 — 목표가·타결 상한을 다시 잡거나, 가격 근거 카드를 교체해 보세요.',
[CloseReason.OPEN_EQUAL]: '동가로 개찰됐습니다 — 동가 업체만 다시 부르고, 가격 외 조건(납기·수량) 카드를 넣어 보세요.',
[CloseReason.OPEN_NOSHOW]: '전원 미응찰로 개찰됐습니다 — 마감기한을 늘리거나 부를 공급사를 바꿔 보세요.',
[CloseReason.OPEN_REJECT]: '협상 거부로 개찰됐습니다 — 거부 사유를 확인하고 카드를 교체해 보세요.',
};
type RegenerateModalProps = {
open: boolean;
/** 직전 라운드(원 견적) — 결과 요약 밴드·협상기간·상한율 기본값의 근거. */
quotation: QuotationData;
/** 직전 라운드 세션 — 공급사별 투찰가·상태와 승계 목표가를 읽는다. */
sessionViews: SessionView[];
/** 현재 견적에 연결된 공급사만. */
partners: Partner[];
/** 공급사별 협상 단계(세션 상태 코드) — 행에 함께 표시. */
sessionStatusBySupplier?: Record<string, number>;
/** 회사 협상카드 카탈로그(재선택 후보). */
cards: NegotiationCard[];
/** 직전 라운드에서 실제 쓴 카드 id — 기본 선택 + '직전 사용' 배지. */
previousCardIds: string[];
/** 적용 중인 견적 세팅의 타결 상한율(‰) — 견적 override 가 없을 때의 기본값. */
settingCeilingRate: number;
/** 카드 게이팅용 상품 정보(시장가 인용 카드 판정). */
productId: string;
internetLowest: number | null;
/** 기본 선택 = 원 라운드의 공급사들. */
defaultSupplierIds: string[];
/** 확정 → 재생성 호출. 성공(true) 시 모달 닫힘. */
onConfirm: (supplierIds: string[]) => Promise<boolean> | boolean;
onConfirm: (input: RegenerateInput) => Promise<boolean> | boolean;
onClose: () => void;
};
// 마감된 견적의 '다음 라운드'를 만들 때 부를 공급사를 고르는 모달.
// 상품·견적번호·협상기간·카드는 원 견적에서 이어받으므로 여기선 공급사만 선택한다.
export function RegenerateModal({ open, partners, sessionStatusBySupplier, defaultSupplierIds, onConfirm, onClose }: RegenerateModalProps) {
// 마감된 견적의 '다음 라운드'를 만드는 모달.
// 상품·견적번호·담당자는 원 견적에서 잠긴 채 이어받고, 직전 라운드가 깨진 원인에 해당하는
// 레버(공급사·마감기한·목표가·타결 상한·협상카드)만 다시 잡게 한다.
export function RegenerateModal({
open,
quotation,
sessionViews,
partners,
cards,
previousCardIds,
settingCeilingRate,
productId,
internetLowest,
defaultSupplierIds,
onConfirm,
onClose,
}: RegenerateModalProps) {
useScrollLock(open); // 모달 열린 동안 배경(부모) 스크롤 잠금
const inheritedTarget = sessionViews.find((s) => s.target_price > 0)?.target_price ?? null;
const inheritedCeilingRate = quotation.done_ceiling_rate ?? settingCeilingRate;
const [selected, setSelected] = useState<string[]>(defaultSupplierIds);
const [dueDate, setDueDate] = useState(() => kstLocalInputAfter(inheritedDurationMs(quotation)));
const [targetPrice, setTargetPrice] = useState(inheritedTarget != null ? String(inheritedTarget) : '');
const [ceilingTouched, setCeilingTouched] = useState(false); // OFF = 원 견적 상한율 그대로
const [ceilingPct, setCeilingPct] = useState('');
const [selectedCardIds, setSelectedCardIds] = useState<string[]>(previousCardIds);
const [cardDetails, setCardDetails] = useState<Map<string, { code: string; title: string; isWildcard: boolean }>>(
() => new Map(cards.filter((c) => previousCardIds.includes(c.id)).map((c) => [c.id, { code: c.code, title: c.title, isWildcard: c.isWildcard }])),
);
const [cardQ, setCardQ] = useState('');
const [submitting, setSubmitting] = useState(false);
const cardSearch = useListCards({ search: cardQ || undefined, size: 30 });
const cardRows = cardQ ? (cardSearch.data?.cards ?? []).map(mapCardData) : cards;
// 공급사 1곳=재협상(1:1), 여러 곳=재견적(1:N) — 백엔드 타입 자동결정과 동일하게 미리 안내.
// 협상카드는 1:1 에서만 발동하므로 카드 선택도 이 값으로 가른다.
const nextIs1v1 = selected.length <= 1;
const targetNum = Number(targetPrice);
const targetValid = Number.isFinite(targetNum) && targetNum > 0;
const effectiveCeilingRate = ceilingTouched && ceilingPct !== '' ? Math.round(Number(ceilingPct) * 10) : inheritedCeilingRate;
// 타결 상한가 = 목표가×(1+율/1000), 10원 반올림(백엔드 박제식과 동일).
const doneCeilingPrice = targetValid ? Math.round((targetNum * (1000 + effectiveCeilingRate)) / 1000 / 10) * 10 : null;
const { blockReason, cardOptions, selectedCardRows } = useCardGating({
cardRows,
productId,
internetLowest,
estimatedTargetPrice: targetValid ? targetNum : null,
open,
selectedCardIds,
cardDetails,
setSelectedCardIds,
setCardDetails,
previousCardIds,
});
if (!open) return null;
const sessionBySupplier = new Map(sessionViews.map((s) => [s.supplier_id, s]));
const previousSet = new Set(previousCardIds);
const keptCardCount = selectedCardIds.filter((id) => previousSet.has(id)).length;
const cardsChanged =
nextIs1v1 && (selectedCardIds.length !== previousSet.size || selectedCardIds.some((id) => !previousSet.has(id)));
const targetChanged = targetValid && inheritedTarget != null && targetNum !== inheritedTarget;
const targetDeltaPct = targetChanged && inheritedTarget ? ((targetNum - inheritedTarget) / inheritedTarget) * 100 : null;
const hint = quotation.close_reason != null ? REGEN_HINT[quotation.close_reason as CloseReason] : null;
const toggle = (id: string) =>
setSelected((prev) => (prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id]));
// 공급사 1곳=재협상(1:1), 여러 곳=재견적(1:N) — 백엔드 타입 자동결정과 동일하게 미리 안내.
const nextTypeLabel = selected.length <= 1 ? '재협상 (1:1)' : '재견적 (1:N)';
const toggleCard = (id: string) => {
const row = cardRows.find((c) => c.id === id);
if (row) setCardDetails((m) => new Map(m).set(id, { code: row.code, title: row.title, isWildcard: row.isWildcard }));
setSelectedCardIds((prev) => (prev.includes(id) ? prev.filter((c) => c !== id) : [...prev, id]));
};
const selectAllCards = () => {
const rows = cardRows.filter((c) => !blockReason(c));
setCardDetails((m) => {
const next = new Map(m);
rows.forEach((r) => next.set(r.id, { code: r.code, title: r.title, isWildcard: r.isWildcard }));
return next;
});
setSelectedCardIds((prev) => [...new Set([...prev, ...rows.map((r) => r.id)])]);
};
const handle = async () => {
if (submitting || selected.length === 0) return;
if (!isFutureLocalInput(dueDate)) {
showToast('마감기한은 현재 시각보다 나중으로 설정해 주세요.', 'error');
return;
}
if (!targetValid) {
showToast('목표가를 0보다 큰 값으로 입력해 주세요.', 'error');
return;
}
setSubmitting(true);
try {
const ok = await onConfirm(selected);
const ok = await onConfirm({
supplierIds: selected,
dueDate,
// 승계와 같은 값은 안 보낸다 — 서버가 직전 라운드 값을 그대로 이어쓰게 둔다.
targetPrice: targetChanged ? targetNum : null,
cardIds: cardsChanged ? selectedCardIds : null,
doneCeilingRate: ceilingTouched && ceilingPct !== '' ? Math.round(Number(ceilingPct) * 10) : null,
});
if (ok) onClose();
} finally {
setSubmitting(false);
@@ -45,57 +166,213 @@ export function RegenerateModal({ open, partners, sessionStatusBySupplier, defau
return (
<div className="fixed inset-0 z-[55] flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
<div className="w-full max-w-3xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
{/* Header */}
<div className="flex items-center justify-between pb-4 border-b border-border">
<div className="flex items-center gap-2">
<RefreshCw className="text-foreground" size={16} />
<Typography variant="small" className="font-bold">다음 견적 재생성</Typography>
<Typography variant="small" className="font-bold">
다음 견적 재생성 <span className="text-muted-foreground font-normal">· {quotation.round ?? 1}차 → {(quotation.round ?? 1) + 1}차</span>
</Typography>
</div>
<button onClick={onClose} className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer">
<X size={18} />
</button>
</div>
{/* Body */}
<div className="my-4 space-y-3 text-xs">
<Typography as="span" variant="small" className="text-muted-foreground block leading-relaxed">
상품 · 견적번호 · 협상기간 · 카드는 이 견적에서 이어받습니다. 다음 견적에 부를 공급사만 고르세요.
</Typography>
<div className="border border-border rounded overflow-hidden max-h-56 overflow-y-auto divide-y divide-border bg-background">
{partners.map((part) => {
const isChecked = selected.includes(part.id ?? '');
return (
<label
key={part.id}
className="flex items-center justify-between gap-2.5 p-3 hover:bg-muted/30 cursor-pointer transition-colors"
>
<div className="flex items-center gap-2.5 min-w-0">
<input
type="checkbox"
checked={isChecked}
onChange={() => toggle(part.id ?? '')}
className="accent-primary h-4 w-4 shrink-0"
/>
<div className="min-w-0">
<Typography as="span" variant="small" className="font-semibold block truncate">{part.name}</Typography>
<Typography as="span" variant="small" className="text-muted-foreground">
이메일: {part.managerEmail}
</Typography>
<div className="my-4 space-y-4 text-xs">
{/* ── 직전 라운드 결과 — 무엇을 바꿔야 할지의 근거 ── */}
<Section title="직전 라운드 결과" sub={`${quotation.round ?? 1}차`}>
<ResultSummaryBand quotation={quotation} sessionViews={sessionViews} />
{hint && (
<div className="mt-2 flex items-start gap-2 rounded border border-amber-200 bg-amber-50/60 dark:border-amber-900/50 dark:bg-amber-950/20 px-2.5 py-2">
<Lightbulb size={13} className="mt-0.5 shrink-0 text-amber-600" />
<Typography as="span" variant="small" className="text-[11px] leading-snug">{hint}</Typography>
</div>
)}
</Section>
{/* ── 공급사 ── */}
<Section title="다음 라운드에 부를 공급사" sub={`${selected.length}곳 · ${nextIs1v1 ? '재협상 (1:1)' : '재견적 (1:N)'}`}>
<div className="border border-border rounded overflow-hidden max-h-56 overflow-y-auto divide-y divide-border bg-background">
{partners.map((part) => {
const sv = sessionBySupplier.get(part.id ?? '');
return (
<label
key={part.id}
className="flex items-center justify-between gap-2.5 p-3 hover:bg-muted/30 cursor-pointer transition-colors"
>
<div className="flex items-center gap-2.5 min-w-0">
<input
type="checkbox"
checked={selected.includes(part.id ?? '')}
onChange={() => toggle(part.id ?? '')}
className="accent-primary h-4 w-4 shrink-0"
/>
<div className="min-w-0">
<Typography as="span" variant="small" className="font-semibold block truncate">{part.name}</Typography>
<Typography as="span" variant="small" className="text-muted-foreground">
{sv?.reject_reason ? `거부 사유: ${sv.reject_reason}` : `이메일: ${part.managerEmail}`}
</Typography>
</div>
</div>
</div>
{sessionStatusBySupplier?.[part.id ?? ''] != null && (
<span className="shrink-0 text-[9px] font-mono px-1.5 py-0.5 rounded-full border border-border bg-muted text-muted-foreground">
{sessionStatusLabel(sessionStatusBySupplier[part.id ?? ''])}
</span>
)}
<div className="flex items-center gap-2 shrink-0">
<Typography as="span" variant="small" className="text-[10px] tabular-nums text-muted-foreground">
{sv?.bid_price != null ? `직전 투찰 ₩${sv.bid_price.toLocaleString()}` : '미응찰'}
</Typography>
{sv && (
<span className="text-[9px] font-mono px-1.5 py-0.5 rounded-full border border-border bg-muted text-muted-foreground">
{sessionStatusLabel(sv.status)}
</span>
)}
</div>
</label>
);
})}
</div>
</Section>
{/* ── 이번 라운드 조건 ── */}
<Section title="이번 라운드 조건" sub="비워두면 직전 라운드 값 그대로">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1">
<Typography as="label" variant="label">마감기한</Typography>
<Input
type="datetime-local"
className="text-xs"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
/>
<Typography as="p" variant="small" className="text-[10px] text-muted-foreground">
기본값 = 원 견적과 같은 협상기간.
</Typography>
</div>
<div className="space-y-1">
<Typography as="label" variant="label">목표가</Typography>
<Input
type="number"
min={0}
className="text-xs"
value={targetPrice}
onChange={(e) => setTargetPrice(e.target.value)}
placeholder="직전 라운드 목표가"
/>
<Typography as="p" variant="small" className="text-[10px] text-muted-foreground">
{targetDeltaPct != null
? `직전 목표가 ₩${inheritedTarget?.toLocaleString()} 대비 ${targetDeltaPct > 0 ? '+' : '−'}${Math.abs(targetDeltaPct).toFixed(1)}%`
: '직전 라운드 목표가를 그대로 이어받습니다.'}
</Typography>
</div>
</div>
{/* 타결 상한 — 목표가 초과 허용폭. 봇이 이 이하로 합의하면 타결. */}
<div className="mt-3 space-y-1.5">
<div className="flex items-center justify-between">
<Typography as="label" variant="label">타결 상한가</Typography>
<label className="flex items-center gap-1.5 cursor-pointer">
<Typography as="span" variant="small" className="text-[10px] text-muted-foreground">이 라운드만 조정</Typography>
<Switch
checked={ceilingTouched}
onCheckedChange={(on) => {
setCeilingTouched(on);
if (on && ceilingPct === '') setCeilingPct(String(inheritedCeilingRate / 10)); // 켤 때 원 견적값에서 출발
}}
/>
</label>
);
})}
</div>
<div className="flex items-center justify-between text-[11px] text-muted-foreground">
<span>선택: <b className="text-foreground">{selected.length}</b>곳</span>
<span>유형: <b className="text-foreground">{nextTypeLabel}</b></span>
</div>
{ceilingTouched ? (
<div className="flex items-center gap-1.5">
<Typography as="span" variant="small" className="text-[11px] text-muted-foreground">목표가 +</Typography>
<Input
type="number"
step="0.5"
min={0}
className="h-8 w-20 text-xs text-right"
value={ceilingPct}
onChange={(e) => setCeilingPct(e.target.value)}
/>
<Typography as="span" variant="small" className="text-[11px] text-muted-foreground">%</Typography>
</div>
) : (
<Typography as="p" variant="small" className="text-[11px] text-muted-foreground">
원 견적 설정 <span className="font-semibold text-foreground">목표가 +{inheritedCeilingRate / 10}%</span> 유지
</Typography>
)}
<Typography as="p" variant="small" className="text-[10px] text-muted-foreground leading-snug">
{doneCeilingPrice != null
? <>최종 합의가가 <span className="font-bold text-foreground">₩{doneCeilingPrice.toLocaleString()}</span> 이하면 타결, 초과하면 결렬.</>
: '목표가가 정해지면 타결 상한가가 자동 계산됩니다.'}
</Typography>
</div>
</Section>
{/* ── 협상카드 재선택 (1:1 전용) ── */}
<Section
title="협상카드"
sub={nextIs1v1 ? `${selectedCardIds.length}장 · 직전 유지 ${keptCardCount}/${previousSet.size}` : '1:N 재견적은 카드 미발동'}
>
{nextIs1v1 ? (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Typography as="span" variant="small" className="text-[10px] text-muted-foreground">
직전 라운드 카드가 기본 선택돼 있습니다 — 같은 멘트를 다시 던지지 않으려면 교체하세요.
</Typography>
<div className="flex items-center gap-1.5">
<Button type="button" variant="outline" size="sm" className="h-7 px-2.5 text-[11px] gap-1" onClick={selectAllCards}>
<CheckCheck size={13} />
현재 목록 전체선택
</Button>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 px-2.5 text-[11px] gap-1 text-muted-foreground"
onClick={() => setSelectedCardIds([])}
disabled={selectedCardIds.length === 0}
>
<X size={13} />
전체해제
</Button>
</div>
</div>
<Combobox
variant="inline"
multiple
values={selectedCardIds}
options={cardOptions}
loading={cardSearch.isLoading}
onQueryChange={setCardQ}
onToggle={(opt) => toggleCard(opt.id)}
searchPlaceholder="카드명·번호·스크립트 검색..."
emptyText="협상카드가 없습니다"
maxListHeight="max-h-60"
/>
<SelectedCardTable rows={selectedCardRows} onRemove={toggleCard} />
</div>
) : (
<Typography as="p" variant="small" className="text-[11px] text-muted-foreground">
공급사를 2곳 이상 고르면 최저가 자동 낙찰(1:N)이라 협상카드가 쓰이지 않습니다. 카드는 원 견적 그대로 둡니다.
</Typography>
)}
</Section>
{/* ── 생성 직전 변경 요약 ── */}
<div className="rounded border border-border bg-muted/30 px-3 py-2">
<Typography as="span" variant="small" className="text-[10px] text-muted-foreground block mb-1">
{quotation.round ?? 1}차 대비 변경
</Typography>
<Typography as="p" variant="small" className="text-[11px] leading-snug">
{[
`공급사 ${defaultSupplierIds.length}곳 → ${selected.length}곳`,
targetChanged ? `목표가 ₩${inheritedTarget?.toLocaleString()} → ₩${targetNum.toLocaleString()}` : '목표가 유지',
cardsChanged ? `카드 ${previousSet.size}장 → ${selectedCardIds.length}장` : '카드 유지',
ceilingTouched && ceilingPct !== '' ? `타결 상한 +${ceilingPct}%` : '타결 상한 유지',
].join(' · ')}
</Typography>
<Typography as="p" variant="small" className="text-[10px] text-muted-foreground mt-1 leading-snug">
상품 · 견적번호 · 담당자는 원 견적에서 그대로 이어받습니다. 생성해도 초청 메일은 자동 발송되지 않습니다.
</Typography>
</div>
</div>
@@ -117,3 +394,24 @@ export function RegenerateModal({ open, partners, sessionStatusBySupplier, defau
</div>
);
}
/** 원 견적의 협상기간(ms). 백엔드 승계식과 같은 1시간 하한을 적용한다. */
function inheritedDurationMs(quotation: QuotationData): number {
const start = new Date(quotation.start_time ?? '').getTime();
const end = new Date(quotation.end_time ?? '').getTime();
const span = Number.isFinite(start) && Number.isFinite(end) ? end - start : 0;
return Math.max(span, 60 * 60 * 1000);
}
/** 모달 안의 한 섹션 — 제목줄 + 본문. */
function Section({ title, sub, children }: { title: string; sub?: string; children: ReactNode }) {
return (
<div className="space-y-2">
<div className="flex items-baseline justify-between gap-2">
<Typography as="span" variant="label">{title}</Typography>
{sub && <Typography as="span" variant="small" className="text-[10px] text-muted-foreground">{sub}</Typography>}
</div>
{children}
</div>
);
}
@@ -23,11 +23,13 @@ import {
mapServerSessionView,
mapServerCardView,
chainRoundState,
type NegotiationCard,
} from '../../types';
import { QuotationStatus } from '@/api/generated/model';
import { DrawerHeaderCards } from './DrawerHeaderCards';
import { RoundTimeline } from './RoundTimeline';
import { RegenerateModal } from './RegenerateModal';
import type { RegenerateInput } from '../../hooks/useQuotations';
import { SessionsStatusTab } from './SessionsStatusTab';
import { TargetPriceModal } from './TargetPriceModal';
import { QuotationCardsTab } from './QuotationCardsTab';
@@ -42,8 +44,10 @@ type QuotationDetailSheetProps = {
onAward: (qtId: string, winnerSupplierId: string, winnerName: string) => Promise<boolean>;
/** 라운드 타임라인에서 다른 차수로 전환(같은 견적번호의 다른 견적 상세 열기). */
onSwitchRound: (qtId: string) => void;
/** 마감된 견적의 다음 라운드를 수동 생성(공급사 선택). 성공 시 새 qt_id 반환. */
onRegenerate: (qtId: string, supplierIds: string[]) => Promise<string | null>;
/** 마감된 견적의 다음 라운드를 수동 생성(공급사·기한·목표가·카드 재선택). 성공 시 새 qt_id 반환. */
onRegenerate: (qtId: string, input: RegenerateInput) => Promise<string | null>;
/** 재생성 모달의 협상카드 재선택 후보(회사 카드 카탈로그). */
cards: NegotiationCard[];
/** 협상 초청 메일 — 견적 단위(미발송 세션 전체) 발송. */
onNotify: (qtId: string) => Promise<void>;
/** 협상 초청 메일 — 세션(공급사) 단위 재발송. */
@@ -55,6 +59,7 @@ type QuotationDetailSheetProps = {
export function QuotationDetailSheet({
quotation,
cards,
onCloseQuotation,
onAward,
onSwitchRound,
@@ -98,11 +103,15 @@ export function QuotationDetailSheet({
const serverCards = cardsQuery.data?.cards ?? [];
// 재생성 모달 기본 선택 = 이 라운드에 부른 공급사들(세션 distinct supplier).
const currentSupplierIds = [...new Set(serverSessions.map((s) => s.supplier_id))];
// 재생성 모달엔 '현재 견적에 연결된 공급사'만 + 각자의 협상 단계(세션 상태)를 함께 보여준다.
// 재생성 모달엔 '현재 견적에 연결된 공급사'만 + 각자의 협상 단계·직전 투찰가를 함께 보여준다.
const connectedPartners = partners.filter((p) => currentSupplierIds.includes(p.id ?? ''));
const sessionStatusBySupplier: Record<string, number> = Object.fromEntries(
serverSessions.map((s) => [s.supplier_id, s.status]),
);
// 재생성 카드 재선택 기본값 = 이 라운드가 실제로 쓴 카드.
const previousCardIds = serverCards
.map((c) => c.nego_card_id ?? c.wild_card_id ?? '')
.filter((id): id is string => !!id);
// 타결 상한율(‰) — 견적 override 가 없으면 적용 중인 견적 세팅값이 기본.
const settingCeilingRate =
quotationSettings.find((qs) => qs.qt_setting_id === quotation.qt_setting_id)?.done_ceiling_rate ?? 50;
// 재생성 버튼은 '체인의 마지막 차수(마감됨)'에서만 노출. 체인 로딩 끝난 뒤 판정해 옛 라운드에서 깜빡임 방지.
const { rounds: chainRounds, isLoading: chainLoading } = useQuotationChain(quotation.number);
@@ -351,14 +360,21 @@ export function QuotationDetailSheet({
);
})()}
{regenOpen && (
{/* 카드·세션이 도착한 뒤에 열어야 '직전 라운드 카드' 기본선택과 결과 요약이 제 값으로 뜬다. */}
{regenOpen && !cardsQuery.isLoading && !sessionsQuery.isLoading && (
<RegenerateModal
open
quotation={quotation}
sessionViews={sessionViews}
partners={connectedPartners}
sessionStatusBySupplier={sessionStatusBySupplier}
cards={cards}
previousCardIds={previousCardIds}
settingCeilingRate={settingCeilingRate}
productId={itemId}
internetLowest={currentItem?.internet_lowest_price ?? null}
defaultSupplierIds={currentSupplierIds}
onConfirm={async (ids) => {
const newId = await onRegenerate(qtId, ids);
onConfirm={async (input) => {
const newId = await onRegenerate(qtId, input);
if (newId) {
onSwitchRound(newId); // 새 라운드 상세로 전환
return true;
@@ -28,16 +28,18 @@ export function QuotationSettingsModal({
const label = useLabels(); // 회사 설정 용어(목표 마진 등)
const [targetMargin, setTargetMargin] = useState('');
const [cardUseCount, setCardUseCount] = useState('');
const [doneCeilingRate, setDoneCeilingRate] = useState('5'); // 협상 완료 상한율(%) 기본 5
if (!open) return null;
// 세팅은 목표 마진율·카드 사용 횟수만. 낙찰 정책은 견적 생성으로 이관, 앵커링은 칸 rate(v1.2)로 대체.
// 세팅은 목표 마진율·카드 사용 횟수·완료 상한율. 낙찰 정책은 견적 생성으로 이관, 앵커링은 칸 rate(v1.2)로 대체.
const handleAdd = (e: React.FormEvent) => {
e.preventDefault();
const ok = onAdd({ targetMargin, cardUseCount });
const ok = onAdd({ targetMargin, cardUseCount, doneCeilingRate });
if (ok) {
setTargetMargin('');
setCardUseCount('');
setDoneCeilingRate('5');
}
};
@@ -65,13 +67,14 @@ export function QuotationSettingsModal({
<TableRow>
<TableHead className="p-2">{label('target_margin')}</TableHead>
<TableHead className="p-2">카드 사용 횟수</TableHead>
<TableHead className="p-2">타결 상한율</TableHead>
<TableHead className="p-2 text-center w-12">삭제</TableHead>
</TableRow>
</TableHeader>
<TableBody className="divide-y divide-border bg-background">
{settings.length === 0 && (
<TableRow>
<TableCell colSpan={3} className="p-6 text-center text-muted-foreground">
<TableCell colSpan={4} className="p-6 text-center text-muted-foreground">
등록된 견적 세팅이 없습니다. (리스트가 비어 있습니다)
</TableCell>
</TableRow>
@@ -80,6 +83,7 @@ export function QuotationSettingsModal({
<TableRow key={qs.qt_setting_id} className="hover:bg-muted/30">
<TableCell className="p-2 font-bold text-primary">{qs.target_margin}</TableCell>
<TableCell className="p-2 text-muted-foreground">{qs.card_use_count}</TableCell>
<TableCell className="p-2 text-muted-foreground">{qs.done_ceiling_rate / 10}%</TableCell>
<TableCell className="p-2 text-center">
<button
type="button"
@@ -109,6 +113,11 @@ export function QuotationSettingsModal({
<Typography as="label" variant="muted" className="text-[10px] font-semibold">카드 사용 횟수</Typography>
<Input type="number" step="1" value={cardUseCount} onChange={(e) => setCardUseCount(e.target.value)} placeholder="예: 3" />
</div>
<div className="space-y-1">
<Typography as="label" variant="muted" className="text-[10px] font-semibold">타결 상한율 (%)</Typography>
<Input type="number" step="0.5" value={doneCeilingRate} onChange={(e) => setDoneCeilingRate(e.target.value)} placeholder="예: 5" />
<Typography as="p" variant="muted" className="text-[9px] leading-tight">목표가를 이 폭까지 넘어도 타결로 인정(목표가×(1+%)). 초과하면 결렬.</Typography>
</div>
</div>
<div className="flex justify-end pt-2">
@@ -12,7 +12,12 @@ export function nowKstLocalInput(): string {
}
export function defaultDueDateLocalInput(): string {
return toKstLocalInput(new Date(Date.now() + 60 * 60 * 1000));
return kstLocalInputAfter(60 * 60 * 1000);
}
// 지금부터 ms 뒤 시각. 재생성 모달이 '원 견적과 같은 협상기간'을 마감기한 기본값으로 채울 때 쓴다.
export function kstLocalInputAfter(ms: number): string {
return toKstLocalInput(new Date(Date.now() + ms));
}
export function isFutureLocalInput(value: string): boolean {
@@ -16,6 +16,8 @@ type UseCardGatingParams = {
cardDetails: Map<string, CardDetail>;
setSelectedCardIds: Dispatch<SetStateAction<string[]>>;
setCardDetails: Dispatch<SetStateAction<Map<string, CardDetail>>>;
/** 직전 라운드에서 쓴 카드 id — 목록에 '직전 사용' 배지를 달아 같은 멘트를 또 던지는 걸 눈에 띄게 한다(재생성 전용). */
previousCardIds?: string[];
};
// 카드 선택 게이팅 — 협상 멘트에 변수 토큰이 그대로 노출되거나 논리가 모순되는 카드를 선택 단계에서 막는다.
@@ -30,7 +32,9 @@ export function useCardGating({
cardDetails,
setSelectedCardIds,
setCardDetails,
previousCardIds,
}: UseCardGatingParams) {
const previousSet = new Set(previousCardIds ?? []);
// (1) 조건 전략(customer_condition) 미작성 — 저장 시 조건 내용이 있으면 script 에 실제 문구가
// 주입되고(slate.serialize), 없으면 {customer_condition} 토큰이 그대로 남는다.
const conditionUnfilled = (c: NegotiationCard) =>
@@ -81,6 +85,11 @@ export function useCardGating({
<span className={`text-[9px] font-mono px-1.5 py-0.5 rounded leading-none ${card.isWildcard ? 'bg-amber-50 text-amber-700' : 'bg-zinc-100 text-zinc-600'}`}>
{card.isWildcard ? '와일드' : '협상'}
</span>
{previousSet.has(card.id) && (
<span className="text-[9px] font-mono px-1.5 py-0.5 rounded leading-none bg-violet-50 text-violet-700">
직전 사용
</span>
)}
{reason && (
<span className="text-[9px] font-mono px-1.5 py-0.5 rounded leading-none bg-rose-50 text-rose-600">
{reason}
@@ -45,11 +45,22 @@ export type CreateQuotationInput = {
// 낙찰 기준 — 1:1 협상만 전송(경매는 미전송 → 서버가 mid=over=AWARD 강제). 2전략을 mid/over 로 전개해 담는다(over 항상 OPEN).
midAction?: number; // PriceGateAction (앵커~목표가 처리: 낙찰/개찰)
overAction?: number; // PriceGateAction (목표가 초과 처리: 협상은 항상 개찰)
doneCeilingRate?: number; // 협상 완료 상한율(‰) 이 견적 override. 미전송이면 세팅 기본값
};
// 재생성 확정값 — 공급사·마감기한은 항상 확정해 보내고, 나머지는 바꾼 것만(null=원 견적 값 승계).
export type RegenerateInput = {
supplierIds: string[];
dueDate: string; // datetime-local 원본값
targetPrice: number | null;
cardIds: string[] | null;
doneCeilingRate: number | null; // ‰
};
export type SettingInput = {
targetMargin: string;
cardUseCount: string;
doneCeilingRate: string; // 협상 완료 상한율(%) 입력값 — 저장 시 ‰(×10)로 변환
};
// 견적 화면 데이터 허브.
@@ -163,14 +174,20 @@ export function useQuotations(params: ListQuotationsParams) {
const addSetting = (input: SettingInput): boolean => {
const marginPct = Number(String(input.targetMargin).replace('%', '').trim());
const cardCount = parseInt(String(input.cardUseCount).replace(/[^0-9-]/g, ''), 10);
const ceilingPct = Number(String(input.doneCeilingRate).replace('%', '').trim());
if (!Number.isFinite(marginPct) || !Number.isInteger(cardCount)) {
showToast(`${label('target_margin')}·카드 사용 횟수를 숫자로 입력해야 합니다.`, 'error');
return false;
}
if (!Number.isFinite(ceilingPct) || ceilingPct < 0) {
showToast('타결 상한율을 0 이상 숫자로 입력해야 합니다.', 'error');
return false;
}
createSettingMutation.mutate(
// 낙찰 정책은 견적 생성으로 이관, 앵커링은 칸 rate(v1.2) → 세팅은 목표 마진율·카드 사용 횟수만.
// 낙찰 정책은 견적 생성으로 이관, 앵커링은 칸 rate(v1.2) → 세팅은 목표 마진율·카드 사용 횟수·완료 상한율.
{ data: {
target_margin_rate: marginPct / 100, card_count: cardCount,
done_ceiling_rate: Math.round(ceilingPct * 10), // % → ‰
} },
{
onSuccess: () => {
@@ -236,6 +253,7 @@ export function useQuotations(params: ListQuotationsParams) {
// 낙찰 기준은 1:1 협상만 전송(모달이 미리 걸러 담음) — 경매면 미전송 → 서버가 AWARD 강제.
mid_action: input.midAction ?? undefined,
over_action: input.overAction ?? undefined,
done_ceiling_rate: input.doneCeilingRate ?? undefined,
};
try {
@@ -258,15 +276,25 @@ export function useQuotations(params: ListQuotationsParams) {
}
};
// 마감된 견적을 골라 다음 라운드를 수동 생성한다(공급사는 프론트 선택, 상품·번호·기간은 원 견적 승계).
// 마감된 견적을 골라 다음 라운드를 수동 생성한다(상품·번호는 원 견적 승계).
// 공급사·마감기한은 모달이 항상 확정해 보내고, 목표가·카드·타결 상한율은 바꾼 것만 보낸다(null=승계).
// 성공 시 새 라운드 qt_id 반환, 실패/검증오류 시 null.
const regenerateQuotation = async (qtId: string, supplierIds: string[]): Promise<string | null> => {
if (supplierIds.length === 0) {
const regenerateQuotation = async (qtId: string, input: RegenerateInput): Promise<string | null> => {
if (input.supplierIds.length === 0) {
showToast('다음 견적에 부를 공급사를 한 곳 이상 선택해 주세요.', 'error');
return null;
}
try {
const res = await regenerateQuotationMutation.mutateAsync({ qtId, data: { supplier_ids: supplierIds } });
const res = await regenerateQuotationMutation.mutateAsync({
qtId,
data: {
supplier_ids: input.supplierIds,
end_time: new Date(input.dueDate).toISOString(),
target_price: input.targetPrice ?? undefined,
card_ids: input.cardIds ?? undefined,
done_ceiling_rate: input.doneCeilingRate ?? undefined,
},
});
const newId = res?.qt_id ?? null;
if (!res?.result?.success || !newId) {
const reason = res?.msg ?? res?.result?.desc ?? '서버 오류';
@@ -21,6 +21,7 @@ type UseTargetPriceParams = {
negoTouched: boolean;
applyNego: boolean;
selectedCandidateKey: string | null;
doneCeilingRateOverride: number | null; // 협상 완료 상한율(‰) 견적 override. null 이면 세팅 기본값
};
// 견적 목표가 산정 — 세팅 네고율·상품 후보(인터넷최저가/매입가/판매가)에서 목표가 후보와 채택값을 파생한다.
@@ -39,6 +40,7 @@ export function useTargetPrice({
negoTouched,
applyNego,
selectedCandidateKey,
doneCeilingRateOverride,
}: UseTargetPriceParams) {
const label = useLabels(); // 회사 설정 용어(목표 마진 등)
const isHidden = useHiddenFields(); // 회사설정으로 감춘 상품 기본필드 — 후보 리스트에서도 제외
@@ -93,6 +95,13 @@ export function useTargetPrice({
: null;
const targetLimitExceeded = targetPriceLimit != null && estimatedTargetPrice != null && estimatedTargetPrice > targetPriceLimit;
// 협상 완료 상한 — 견적 override(‰) 우선, 없으면 세팅 기본. 상한가 = 목표가×(1+율/1000), 10원 반올림(백엔드 박제와 동일).
const settingCeilingRate = Number(selectedSetting?.done_ceiling_rate ?? 50);
const effectiveCeilingRate = doneCeilingRateOverride ?? settingCeilingRate;
const doneCeilingPrice = estimatedTargetPrice != null
? Math.round((estimatedTargetPrice * (1000 + effectiveCeilingRate)) / 1000 / 10) * 10
: null;
return {
settingMarginPct,
negoCandidateKey,
@@ -106,5 +115,8 @@ export function useTargetPrice({
targetLimitExceeded,
estimatedTargetPrice,
submitMdPrice,
settingCeilingRate,
effectiveCeilingRate,
doneCeilingPrice,
};
}
@@ -37,6 +37,7 @@ export interface QuotationSetting {
user_id: string;
target_margin: string;
card_use_count: string;
done_ceiling_rate: number; // 협상 완료 상한율(‰). 완료 상한=목표가×(1+값/1000). 견적생성 모달이 상한가 계산에 직접 사용
created_at: string;
updated_at: string;
deleted: boolean;
@@ -67,6 +68,7 @@ export function mapSetting(s: QuotationSettingData): QuotationSetting {
user_id: s.user_id || '',
target_margin: `${Number.isFinite(ratePct) ? +ratePct.toFixed(2) : 0}%`,
card_use_count: `${s.card_count ?? 0}회`,
done_ceiling_rate: Number(s.done_ceiling_rate ?? 50), // ‰
created_at: s.created_at ?? '',
updated_at: s.updated_at ?? '',
deleted: false,
+1
View File
@@ -240,6 +240,7 @@ export default function QuotationPage() {
<QuotationDetailSheet
key={activeQuotation.qt_id}
quotation={activeQuotation}
cards={cards}
onCloseQuotation={closeQuotation}
onAward={awardQuotation}
onSwitchRound={(qtId) => overlay.open('detail', qtId, { replace: true })}