Compare commits

..
Author SHA1 Message Date
minaChoi ac6366a898 [feat] negosium·negodata: 협상 진행 중 거부 + 결렬 건 최종 제출가로 직접 낙찰
협력사가 단종·품절을 대화 도중 알아채도 봇의 결렬 선언을 기다려야 했고,
거부로 끝난 협상은 가격을 남겨도 낙찰 후보에서 빠져 계약으로 이어지지 않았다.

negosium
- 채팅 액션바에 협상 거부 진입점 — 대화가 끝나지 않고 입력을 기다리는 동안만 노출,
  주 CTA 와 붙지 않게 넓은 화면은 우측 끝 고정·좁은 화면은 wrap
- 거부 팝업은 목록 거부 팝업과 같은 어휘·규격, 대화 중이라 공급 희망 가격·의견을 더 받는다
- /reject 에 reject_price·opinion 추가 — sessions.reject_price 저장, 의견은 custom 병합
- 화면 문구 '거절' → '거부' 통일 (버튼·배지·탭·토스트·안내 팝업)

negodata
- 개찰 견적 직접 낙찰 후보 = 가격을 써낸 세션 — 투찰한 협상완료 + 공급 희망가를 남긴 협상거부
- 계약가 파생 _award_price/awardPrice — coalesce(투찰가, 거부 시 공급 희망가)
- 통계 낙찰 세션 조인도 같은 기준 — 안 고치면 거부가로 낙찰한 건이 절감 집계에서 빠진다
- 세션 상태 탭 라벨 '거절사유/거절가격/거절배송방식' → '거부…'

자동 마감 판정(close_and_decide)은 그대로 — 자동 낙찰은 투찰가만 본다.
2026-08-11 10:34:07 +09:00
minaChoi f1e924931f [fix] negodata: 협상 학습 화면 정리 — 내부 점수 제거·카드탭 사용 현황 전환·메뉴 개발자 전용
- 관측 사실 기준으로 재구성: 내부 점수 제거, 앵커링 % 표기, 탭 URL 분리
- 카드탭을 성과 지표에서 사용 현황으로 전환, 지표 설명 말풍선·카드 상세 링크
- 사이드바 devOnly + 라우트 가드로 개발자 전용 처리
2026-08-11 08:49:15 +09:00
minaChoi e1e519c20c [fix] negosium/backend·front: 마감된 협상이 '협상 대기'로 보이던 문제 + 종료 협상 결과 보기
- 목록 상태를 파생 계산(_effective_status): 견적 마감/마감시간 경과 + 협상생성(1) → 미참여(4).
  표시·상태필터·기본정렬 그룹에 같이 적용해 탭·KPI 카운트가 배지와 어긋나지 않게 함(DB 쓰기 없음).
  마감 일괄정리 이후 생긴 세션이 '협상 대기'에 남아 눌러도 마감 에러가 나던 헛클릭 제거.
- 미참여·협상거부 세션도 채팅 init 허용 → '결과 보기'로 지난 대화 열람. 대화 재개는 send 가
  협상중만 허용해 읽기 전용. 열 게 없는 건은 목록 has_chat(대화 이력 유무)으로 버튼 자체를 감춤.
- 종료 건은 참여 API 를 타지 않고 채팅으로 직행, 채팅 액션바는 목록 복귀만 남겨 입력 잠금.
- chain_max_round 가 단일컬럼 select 결과를 행 튜플로 읽어 매 목록 호출마다 예외 → 체인 최대차수
  0 → 옛 라운드에도 재협상 요청이 뜨고 통과되던 버그 수정(+ABC 에 중복된 죽은 구현 제거).
2026-08-10 13:57:30 +09:00
minaChoi e816bfbba4 [feat] negodata: 협상 학습 메뉴 신설 — 카드별 학습 성적 · 앵커링 현황/조정 이력
agent(협상카드 강화학습)와 anchoring(구간별 자동 조정)이 쌓아온 결과를 볼 수 있는 화면이
없어 DB 를 직접 열어야 확인이 됐다. 두 축은 성격이 달라 한 화면에 섞지 않고 탭으로 나눈다.

백엔드(읽기 전용 — 값의 주인은 agent·anchoring):
- crud/learning_crud.py: learning·anchoring 스키마 경량 조회(negodata ORM 미매핑 테이블)
- services/learning_service.py + router/v1/learning: /v1/learning/cards · /anchoring

프론트:
- 사이드바 '협상 학습'(/learning) 추가, 탭 = 협상카드 | 앵커링
- 협상카드: 학습 협상·기록·타결 비율 요약 + 카드별 사용/타결/평균 점수(0 기준 좌우 막대)
- 앵커링: 구간별 현재 인하폭 + 조정 이력(표본·성공률·값 변화)

검증: 로컬 실협상 3건으로 데이터 생성 후 두 탭 실화면 확인, tsc·eslint 통과.
2026-08-10 13:24:32 +09:00
minaChoi 37fa65707f [fix] postgres-init: 카드 시드를 운영 현행에 맞춤 — 중반 카드 앵커가 인용 + 목표가 카드 종결 전용
협상 중반에 목표가를 부르면 이후 올려줄 금액이 없어져 남은 카드가 같은 값만 반복한다.
제안은 앵커가 → 중간가 → 목표가로 수렴해야 하므로 시드를 그 순서에 맞춘다.

- NGC-010 향후 거래 연계 · NGC-011 양보 가치 강조: 제시 금액 {target_price} → {anchor_price}
- tactic: WC-01 종결 전용 추가, WC-04 min_round 2 → 종결 전용, WC-05 종결 전용 + min_round 2,
  WC-02 min_round 2 추가 (WC-03 종전 유지)

init-data.sql · dbeaver/4_cards_reset_dbeaver.sql 동일 반영.
검증: 임시 DB 에 1_init + 4_cards_reset 적용 후 tactic·변수 확인.
2026-08-10 11:41:25 +09:00
minaChoi 86d50c1291 [fix] negodata/front: 윈도우 모달 한글 깨짐 — 컨테이너 font-mono 제거 + 모노 스택 한글 폴백
모달 래퍼·폼에 걸린 font-mono 가 내부 한글까지 모노 스택으로 태웠다. JetBrains Mono·Consolas 에
한글 글리프가 없어 Windows 에서 굴림으로 떨어졌다(맥은 뒤쪽 폰트가 한글을 커버해 정상으로 보임).

- 한글이 들어가는 컨테이너 15곳에서 font-mono 제거 — 숫자 정렬이 필요한 칸은 유지
- --font-mono 스택 끝에 'Noto Sans KR' 추가, index.html 에 구글폰트 링크
  (self-host Pretendard 가 못 뜰 때의 안전망 — 정상 경로는 동일 도메인 Pretendard)
2026-08-10 09:49:26 +09:00
minaChoi 436384fa36 [fix] agent: 중간값 카드가 목표가로 제시되던 문제 — 제안가 산식 일원화·절충 카드 목표가 이상 미발동·적용 대기 와일드카드 차단
원인 두 겹.
1) 절충 계열 가드가 타결 상한만 봐서, 중간가((앵커+목표)/2)처럼 구조상 목표가를 넘지 못하는
   값은 항상 통과했다. 앵커가 목표가에 붙으면 그 값이 곧 목표가라 목표가로 제시된다.
   → 파생 제안값이 목표가 이상이면 미발동(compute_offer). 목표가 카드는 영향 없음.
2) 제안가 확정 시 계산에 쓴 당사 직전가를 남기지 않고 그 자리를 제안가로 덮은 뒤, 멘트 렌더가
   갱신된 값으로 재계산해 "당사 A 와 귀사 B 의 절반은 A" 자기모순이 났다. 직전 커밋은 갱신을
   렌더 뒤로 미뤘으나 와일드카드는 렌더 지점이 더 뒤라 그대로 남아 있었다.
   → Offer/record_offer 로 금액과 재료(당사 직전가·협력사 제시가)를 함께 박제하고, vars_for 는
     재계산 대신 그 기록을 읽는다. 렌더 순서에 의존하지 않으므로 직전 커밋의 순서 조정은 제거.
   → 산식은 tactics.OFFER_VARIABLES 한 곳만 남기고 chat_engine 의 복사본 삭제.

곁들여: 카드 설정에서 '적용 대기'로 꺼둔 와일드카드가 견적에 담겨 있으면 그대로 발동하던 것을
차단(wild_cards.available 조건). 테이블 정의에 빠져 있던 컬럼도 보강.

검증: 단위/E2E 35건, 실협상 8시나리오(멘트 토큰 노출·절반 산술 정합·카드 중복·제안가 역행·
상한 초과 자동 검사) 통과.
2026-08-10 09:45:30 +09:00
minaChoi a405e00bf9 [fix] agent·negodata/front: 중간값 멘트 모순 수정(갑 포지션 갱신을 치환 뒤로·원값 인용가 반올림 제외·1% 카드 역행 금지) + 계정 전환 쿼리캐시 초기화·ChatTab 카드 렌더 정리 + font-mono 한글 폴백(Windows 한글깨짐) 2026-08-07 15:48:48 +09:00
민헌andClaude Opus 5 7dc925bcd4 docs(lps): 2026-08-07 세션 기록 — IP 로테이션 검수·네이버 UA 규명·결과 상태 정의
다음 세션이 이어받을 수 있게 남긴다.

- docs/2026-08-07-session-notes.md 신규: 세 덩어리(IP 로테이션 결함 6개, 네이버 컨테이너 차단이
  실은 UA 플랫폼 토큰이었다는 규명, '못 봤다'를 '없다'고 말하던 문제의 4단계 해결)와
  **되돌리기 전에 볼 근거**(예산을 IP 에 묶는 이유, 태우지 않는 판정, 임대 없이 크롤 금지,
  UA 는 플랫폼만 바꾸고 버전은 실값, 상태는 하나로 저장하고 표시에서 접기).
- 미해결: 쿠팡 간헐 차단 — IP 에 따라 갈리므로 환경이 아니라 평판. 쿠팡만 gate(해외 IP)를 쓰는 게
  유력한 원인이고, 네이버처럼 kr_host 로 바꾸는 검증이 중단된 상태.
- 다음 할 일 5가지(운영 마이그레이션 → 쿠팡 KR 검증 → 예산 튜닝 → AI 매칭 정확도 → admin 잡목록).
- 주의사항 5가지: **마이그레이션→코드 순서 강제**(역순이면 최저가 조회가 통째로 실패, 재현 확인),
  워커 켜고 pytest 하면 test_job_queue 3개 깨짐, JS 지문 위장은 patchright 가 막아 불가,
  로컬 negodata-front 는 node_modules 가 named volume 이라 재빌드로 의존성이 안 늘어남.
- README 문서 표에 링크 추가.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 15:02:25 +09:00
민헌 0c6c431f0a Merge branch 'feat/source-state'
'못 봤다'를 '없다'고 말하던 문제를 4단계로 해결한다. 상태를 하나로 정의·저장하고 표시 단계에서
보는 사람에 맞게 접는다 — 운영자(lps-admin)는 7상태 그대로, 실사용자(negodata)는 셋으로.

1) SourceState 7상태 — 어댑터가 이미 알던 '봤다/못 봤다' 구분을 핸들러가 버리지 않게 한다
2) price_history.sources/partial — 그 구분을 담을 자리(by_mall 은 가격 있는 몰만 담는다)
3) lps-admin — 몰별 상태·차단 마커·조치 힌트(blocked=자동회복 vs env_blocked=사람이 고쳐야)
4) negodata — '–'(확인했고 없음)와 '확인 못함'(못 봄)을 가르고, 후자는 재검색 대상으로 남긴다

⚠️ 배포 순서: 마이그레이션 2개(6_lps_2026-08_dbeaver.sql · 2026-08-07-iilp-source-state.sql)를
   **코드보다 먼저** 적용해야 한다. negodata 가 ORM 전체 엔티티를 조회하므로 컬럼이 없으면
   최저가 조회가 통째로 실패한다(재현 확인). 역순(마이그레이션 후 옛 코드)은 안전하다.

실환경 검증: 실제 크롤 결과로 네이버 no_match→'–', 쿠팡 env_blocked→'확인 못함' 확인.
잡 DEAD 0건, 네거티브 캐시 미오염, 포트 소각 8/100 에서 차단.
2026-08-07 14:46:02 +09:00
민헌 67612b477c Merge remote-tracking branch 'origin/main' into feat/source-state 2026-08-07 14:36:41 +09:00
민헌andClaude Opus 5 6e401615eb fix(negodata): '일부 확인 못함'을 결과 열에도 표시 — 몰 칸만 고쳐 놓친 부분
실화면 확인에서 드러났다. 쿠팡 칸은 '확인 못함'으로 잘 나오는데 결과 열이 '변동 없음'이었다.
못 본 몰이 있는데 '변동 없음'이라 하면 사용자는 여전히 "이 가격이 최종이구나"로 읽는다 —
그 몰에 더 싼 값이 있었을 수 있어 이 결과는 최종이 아니다.

docs/result-states.md 3-2절에 이미 정의해 둔 표기인데(| 일부 확인 못함 | partial |)
몰 칸만 구현하고 결과 열을 빠뜨렸다.

- 결과 열: unconfirmed 가 있으면 '일부 확인 못함'(툴팁에 어느 몰인지). '탐색 성공'(더 싸게 찾음)은
  그대로 우선한다 — 값이 실제로 갱신된 건 사실이므로.
- 재검색 대상: 못 본 몰이 있으면 **완료로 치지 않는다**. 가격이 갱신됐어도 다음 '다시 검색'의
  기본 대상으로 남긴다 — 그게 '다시 시도할 이유가 생긴다'의 실제 동작이다.

tsc 오류 없음. 실데이터로 확인(섬유유연제: 네이버 4,820 matched · 쿠팡 blocked/env_blocked).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 14:29:15 +09:00
minaChoi 11b29b45e3 [fix] negodata·frontend·backend: 회사별 브랜드 색(primary_color) 기능 전면 제거 — 편집 UI 없이 값만 남아 적용되던 구현 정리(포털·메일·사이드바 색 솔루션 고정, 시드·응답 필드 제거) 2026-08-07 13:45:23 +09:00
minaChoi 4ed23c56b8 [feat] negodata: IMK 요청 일괄 반영 — 조회 게이팅·카드 매칭·부가세 통일 모드·기준가 이원 표기·마스킹 해제·이미지 일괄 업로드·초청메일 브랜딩·반응형 정리 2026-08-07 11:57:06 +09:00
민헌andClaude Opus 5 6ddb2c4504 refactor(postgres-init): LPS 2026-08 마이그레이션 6_·7_ 통합 + 주석 스타일 정리
같은 DB(lps_db)의 같은 시기 추가분이 두 파일로 갈려 있어 순서·누락을 신경 써야 했다.
6_ 하나로 합친다(7_ 삭제) — 실행이 한 번이면 '어디까지 돌렸더라'를 기억할 일이 없다.

- 주석을 3_lps_dbeaver.sql 스타일로 통일: 객체 위 한 줄 설명 + 컬럼 인라인 주석 정렬.
  기존 6_·7_ 의 긴 배경 산문은 걷어냈다 — 배경은 lps/docs/result-states.md 가 소스고,
  이 파일은 '무엇을 만드는가'만 답하면 된다.
- 내용은 그대로: proxy_port(+LRU 인덱스), price_history 신뢰 신호 2·배송 3,
  몰별 확인 상태 sources/partial(+부분 인덱스), 적용 확인 SELECT.

검증: 기존 lps_db 재실행(멱등 — NOTICE 만) + 빈 DB 에 3_ → 6_ 신규 설치 후
price_history 신규 7컬럼·테이블 6종 전부 확인. 테스트 DB 는 정리.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 11:25:22 +09:00
민헌andClaude Opus 5 95086cb3f6 feat(negodata): 4단계 — 사용자 화면에서 '없음'과 '확인 못함'을 구분
마지막 단계. 차단당해 못 본 몰이 화면에서 '–'(없음)로 보여 사용자가 "쿠팡엔 더 싼 게 없구나"로
오해하던 문제를 끝낸다. 안 본 걸 없다고 말하지 않는다.

사용자 화면은 **셋으로 접는다**(lps/docs/result-states.md 3-2절). 할 수 있는 행동이
'쓴다/다시 시도/넘어간다' 뿐이라, 원인이 달라도 다음 행동이 같으면 같은 표기다:
  matched                            → 가격
  no_match · empty                   → '–'        (확인했고 없었다)
  blocked · env_blocked · unavailable → '확인 못함' (못 봤다)
운영자 화면(lps-admin)은 같은 데이터로 7상태를 그대로 본다 — 목적이 진단이라 접지 않는다.

체인 전체를 이었다:
- postgres-init/alters/2026-08-07-iilp-source-state.sql — item_internet_lowest_prices 에
  sources/partial 추가(멱등, **운영 적용 필요**)
- models.py / lps_sync_crud 읽기 계약 / lps_sync_service 미러링 / LowestPriceEntry 프로토콜
- orval 재생성(ORVAL_INPUT 으로 저장 스펙에서 — 서버 없이). 생성 diff 는 새 필드만.
- PriceUpdateModal: 가격이 없는 몰이 '못 본 몰'이면 '–' 대신 '확인 못함'.

partial 은 LPS 가 판단해 내려준 사실을 그대로 쓴다 — 화면이 '어떤 상태가 확인된 것인가'를
다시 판정하면 상태 정의가 LPS 와 negodata 두 곳으로 흩어진다.

E2E 검증(실 DB 2시나리오): by_mall 은 둘 다 naver 뿐인데 쿠팡 칸이 '확인 못함'(차단) / '–'(0건)
으로 갈린다. tsc 오류 없음(기존 xlsx 미설치 오류는 무관). negodata 97 · lps 292 passed.

> 폴더 관례상 negodata 는 인수인계 대상이나, 사용자 요청으로 이번 건도 예외 적용.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 11:21:56 +09:00
민헌andClaude Opus 5 d1d1ed6ec5 feat(lps-admin): 3단계 — 몰별 확인 상태를 운영 화면에 노출
2단계에서 저장한 sources/partial 을 운영자가 볼 수 있게 한다. 운영자 목적은 **진단**이라
상태를 접지 않는다 — blocked(IP 회전으로 자동 회복)와 env_blocked(사람이 환경·설정을 고쳐야 함)를
뭉뚱그리면 회복될 일에 매달리거나 손봐야 할 설정을 방치하게 된다.

API
- /v1/lps/products, /v1/lps/products/{code}/history 둘 다 sources·partial 을 싣는다.
- 이력은 **시점마다** 싣는다. 최신 상태를 과거 시점의 몰별 표 옆에 붙이면 '그때도 막혔던 것처럼'
  보여 오해를 부른다 — 그래서 ProductItem 이 아니라 PricePoint 에 담았다.

화면
- lib/sourceState.ts: 상태별 라벨·색·설명·confirmed 를 한곳에. 미지의 상태가 와도 화면이 깨지지
  않는다(값 그대로 표시 + '모름' 취급). 색은 전부 @theme 토큰 참조(raw hex 금지).
- 상품 목록: partial 이면 '일부 확인 못함' 배지 + 툴팁에 어느 몰인지.
- 몰별 비교 카드 위: 몰별 상태·수집 건수·실패 사유 원문(툴팁). 가격표에 없는 몰이 **왜** 없는지를
  여기서 답한다 — by_mall 은 가격이 있는 몰만 담으므로 그 답이 여기밖에 없다.

검증: ASGI 직접 호출로 두 엔드포인트 응답 확인(한글 사유 포함), tsc 오류 없음.
테스트 3건 추가(목록 노출 / 시점별 상태가 각각 다르게 / 컬럼 추가 이전 옛 행 호환).
전체 292 passed. 진행 상황은 docs/result-states.md 4절.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 11:05:31 +09:00
민헌andClaude Opus 5 74db218410 feat(lps): 2단계 — price_history 에 몰별 확인 상태 저장
1단계에서 만든 SourceState 가 job.result 에만 있어 화면까지 못 갔다. by_mall 은 **가격이 있는
몰만** 담으므로, 빠진 몰이 '거기엔 없더라'인지 '거기를 못 봤다'인지 구분할 자리가 없었다.

- price_history.sources (JSONB): 몰별 상태를 그대로 담는다.
  {"naver": {"state": "matched", "count": 40}, "coupang": {"state": "blocked", "error": "..."}}
  열린 스키마라 몰이 늘거나 근거를 덧붙여도 마이그레이션이 필요 없다(by_mall 과 같은 방침).
- price_history.partial (bool): 결과가 완전한가. sources 에서 유도 가능하지만 컬럼으로 둔다 —
  소비자가 '어떤 상태가 확인된 것인가'라는 판단 규칙까지 알아야 하면 **상태 정의가 두 곳으로
  흩어진다**. 판단은 LPS 가 끝내고 소비자(negodata·lps-admin)는 사실 하나만 읽는다.
- 부분 인덱스 ix_price_history_partial — partial=true 행만 담아 작게 유지(운영 점검·알림용).
- _record_history 가 per_source 를 받아 partial 을 계산해 기록한다. 네거티브 캐시 히트 경로는
  sources 없이 남긴다(부분 결과는 애초에 캐시하지 않으므로 항상 확정).
- 마이그레이션: postgres-init/dbeaver/7_lps_source_state_dbeaver.sql (재실행 안전, **운영 적용 필요**)

검증(로컬 실 DB): 쿠팡 차단 vs 쿠팡 0건은 by_mall 이 둘 다 ['naver'] 로 같지만
partial(true/false)·sources.coupang.state(blocked/empty)가 두 경우를 갈라낸다.
JSONB 는 ensure_ascii=False 로 한글 사유가 깨지지 않는 것도 테스트로 고정.

테스트 3건 추가, 전체 289 passed. 진행 상황은 docs/result-states.md 4절.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 10:57:19 +09:00
민헌andClaude Opus 5 b278f58d9c feat(lps): 1단계 — 몰별 상태 보존, '없음'과 '못 봄'을 가른다
docs/result-states.md 의 1단계. 어댑터는 이미 구분을 알고 있는데 핸들러가 그 정보를 버리고
있었다(per_source[src] = {"error": 문자열}). 그래서 차단당해 못 본 몰이 화면에서 '그 몰엔 없음'
으로 둔갑했다. 새로 알아낼 정보는 없고, 흘리던 걸 잡아두기만 하면 된다.

- common/enums.py: SourceState 7상태 추가(MATCHED/NO_MATCH/EMPTY/BLOCKED/ENV_BLOCKED/
  UNAVAILABLE/SKIPPED). `.confirmed` 프로퍼티로 **'봤다 vs 못 봤다' 경계를 한곳에** 둔다 —
  이 경계가 무너지면 나머지 판단이 전부 틀어지므로 흩어놓지 않는다.
- AdapterError.state: 어댑터가 아는 구분을 실어 보낸다. blocked/fatal 은 '어떻게 대응할까'
  (회전·재시도)를 위한 값이고 state 는 '사용자에게 뭐라 말할까'를 위한 값이라 쓰임이 다르다.
  특히 blocked=False 하나에 결과0건(EMPTY)과 전송실패(UNAVAILABLE)가 섞여 있어 state 없이는
  갈라낼 수 없었다. **기본값은 UNAVAILABLE** — 모르면 '못 봤다'가 안전하다(EMPTY 로 두면
  확인도 안 한 몰을 '없음'으로 단정한다).
- browser_base: raise 지점 5곳에 상태 부여. 핵심 갈림은 0건 종착 한 곳 —
  blocked=False → EMPTY(정말 없다) / blocked=True → BLOCKED(못 봤다).
- _search_round: {"state": ..., "count"|"error": ...} 로 구조화. EMPTY 는 '정상 응답'으로 세어
  (confirmed) 쿠팡에 정말 없을 때 잡이 재시도로 낭비되지 않게 한다.
- _finalize_states: 수집만 된 소스를 AI 판정 뒤 MATCHED/NO_MATCH 로 확정한다. 실패 상태는
  이미 확정이라 덮지 않는다.

검증(9조합 실측): empty → partial=False(확정) / blocked·env_blocked·unavailable → partial=True.
테스트 12건 추가, 전체 286 passed. 진행 상황은 docs/result-states.md 4절에 기록.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 10:47:28 +09:00
민헌andClaude Opus 5 1e966f7121 docs(lps): 결과 상태 — 운영자와 실사용자를 나눠 접는 원칙 추가
보는 사람이 둘인데 하나로 뭉뚱그리고 있었다.
  lps-admin  운영자 — 목적이 **진단**이다. '왜 그랬나'에 답해야 하므로 7상태를 그대로 보고
             차단 마커·ip_request_no·포트까지 붙인다. 특히 blocked(자동 회복)와
             env_blocked(사람이 고쳐야 함)를 반드시 갈라야 한다 — 개입 여부가 갈린다.
  negodata   실사용자 — 목적이 **행동**이다. 할 수 있는 건 '쓴다/다시 시도/넘어간다' 셋뿐이라,
             원인이 달라도 다음 행동이 같으면 같은 표기로 접는다:
               no_match·empty            → '–'        (둘 다 결론은 '이 몰엔 없다')
               blocked·env_blocked·unavailable → '확인 못함' (행동은 '나중에 다시' 하나뿐)

핵심 원칙: **상태는 하나로 정의·저장하고, 접는 건 표시 단계에서 한다.**
저장을 단순화하면 관리자가 원인을 못 보고, 표시를 상세화하면 사용자가 못 읽는다.
두 화면 모두 price_history 를 읽으므로(admin_service 확인) 데이터는 공유하고 투영만 달리한다.

예외 하나: '일부 확인 못함'(partial)은 사용자에게도 접지 않는다. 이건 행동을 바꾸기 때문이다 —
'이 가격이 최종인가'의 답이 달라진다. 다만 사용자에게 필요한 건 어느 몰이 왜 막혔는지가 아니라
결과가 완전하지 않다는 사실 하나다.

남은 일도 4단계로 갱신(1 플래그 보존 → 2 저장 자리 → 3 admin 표시 · 4 사용자 표시).
3·4 는 같은 데이터를 다르게 접는 것이라 병행 가능.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 10:11:40 +09:00
민헌andClaude Opus 5 04b697a9eb docs(lps): 검색 결과 상태 정의 — '못 찾음'과 '못 봄'을 가른다
'가격을 못 찾았다' 한 문장에 뜻이 정반대인 상황이 섞여 있다: 그 몰에 정말 없는 것(사실)과
그 몰이 우리를 막아 못 본 것(미확인). 지금 화면은 둘 다 '–' 로 똑같이 보여준다.
구현 전에 용어를 맞추려고 상태를 정의한다.

코드를 확인해 **실제로 구분 가능한 것**만 정의했다:

몰(소스) 단위 7상태 — 경계는 '사실'(no_match/empty) 대 '미확인'(blocked/env_blocked/unavailable).
앞의 둘은 "없다"고 말해도 되고, 뒤의 셋은 말하면 안 된다.

상품 단위 — found / not_found / error + partial 꼬리표. partial 은 독립 상태가 아니라
found·not_found 에 붙는데, 특히 'not_found + partial' 은 결론이 아니다(못 본 몰에 있었을 수 있음).

확인 과정에서 드러난 근본 원인:
- 어댑터는 이미 구분을 **안다** — AdapterError 에 blocked·fatal 이 있고 detect_block 이
  '차단 vs 정상 빈결과'를 판정한다.
- 그런데 **핸들러가 그 플래그를 버린다**: per_source[src] = {"error": f"{...}"} — 문자열만 남는다.
- 게다가 0건도 예외로 온다(return 은 1건 이상일 때만). 즉 empty 와 blocked 가 둘 다
  AdapterError 로 도착하는데 구분 플래그를 버리므로 이후로는 갈라낼 수 없다.

→ 새로 알아낼 정보는 없다. 이미 아는 걸 흘리고 있을 뿐이라, _search_round 한 곳이 출발점이다.
   남은 일을 1(플래그 보존) → 2(price_history 자리) → 3(화면 표기) 순서로 정리했다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 09:46:23 +09:00
민헌andClaude Opus 5 14bcf1481b fix(negodata): 검색 실패를 '변동 없음'으로 표시하던 문구 정정
LPS 가 outcome='error'(모든 소스 차단)로 내려주는 경우가 화면에서 '변동 없음'으로 보였다.
사용자는 '검색은 잘 됐는데 더 싼 게 없구나'로 읽지만, 실제로는 **가격을 확인조차 못 한** 것이다.
뜻이 정반대라 오해가 크다.

원인: success_yn=false 를 전부 notfound 로 묶었고, notfound 와 done 이 같은 문구('변동 없음')를
쓴다. fail_reason 은 이미 API·프론트 타입까지 내려오는데 쓰이지 않고 있었다.

→ fail_reason='error' 면 failed 로 분류한다. 화면은 '탐색 실패'가 되고, 실패 사유가 함께 뜨며,
   재검색 대상(failedIds)에 포함돼 사용자가 다시 시도할 수 있다 — 확인 못 한 건 재시도가 맞다.
   'not_found'(진짜 못 찾음)는 기존대로 '변동 없음'을 유지한다.

LPS 변경 없음(이미 내려오는 값을 쓴 것). ItemState 주석도 실제 의미에 맞게 정정.
tsc: 이 파일 오류 없음(기존 xlsx 미설치 오류는 무관).

> 폴더 관례상 negodata 는 인수인계 대상이나, 이번 건은 사용자 요청으로 예외 적용.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 09:38:11 +09:00
민헌andClaude Opus 5 152aed9908 fix(lps): 한 소스가 막혀도 잡을 정상 종료 — '탐색 중'에서 멈추던 원인
운영 로그(2026-08-06)에서 드러난 문제. 쿠팡이 막힌 동안 **네이버가 매번 40건을 가져왔는데도**
잡이 전부 DEAD 로 갔다:

  fail 3c0bcaff → DEAD ({'coupang': {'error': 환경 차단}, 'naver': {'count': 40}})

그리고 DEAD 는 price_history 에 행을 남기지 않는다. 이를 폴링하는 negodata 최저가 모달은
받을 결과가 영영 없어 '탐색 중'에서 멈춘다(사용자 화면 확인). 즉 프론트 버그가 아니라
**백엔드가 답을 안 준 것**이다 — 두 증상이 같은 뿌리였다.

원인: 핸들러가 '하나라도 실패했나'(bool)만 보고 무조건 raise 했다. 한 소스가 막혔다고
다른 소스가 멀쩡히 가져온 결과까지 버린 셈이다.

바꾼 것:
- _search_round 가 **성공한 소스 목록**을 돌려준다(bool → list).
- 살아있는 소스가 하나라도 있으면 그 결과로 진행한다. **전부 죽었을 때만** 재시도한다
  ('없음'이라 단정할 수 없는 건 그때뿐이다).
- 결과에 sources_ok/sources_failed/partial 을 실어 커버리지를 드러낸다(부분 결과 로그도 남김).
- 부분 실패 상태의 not_found 는 **네거티브 캐시에 넣지 않는다** — 막힌 소스엔 있었을 수 있는데
  '없음'으로 굳히면 TTL 동안 재검색이 막힌다(사용자가 '다시 검색'을 눌러도 캐시 히트).
- 전부 실패 + 재시도 소진이면 DEAD 대신 outcome='error' 로 **이력을 남기고** 종료한다.
  화면이 무한 대기 대신 결과를 받는 게 중요하다.

negodata 는 변경 없이 받는다(outcome='error' → success_yn=false, fail_reason='error').

테스트 5건 추가·1건 갱신(옛 계약 '한 소스 실패 시 raise' 를 새 계약으로 교체), 전체 274 passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 16:34:36 +09:00
민헌 f483839b11 Merge branch 'fix/naver-container-wtm'
네이버 컨테이너 차단 해결 — 원인은 UA 의 플랫폼 토큰(리눅스)이었다.
네이버가 리눅스 데스크톱 Chrome 을 HTTP 405 로 거부한다: Linux UA 0/3 통과 · Mac UA 3/3 통과
(같은 이미지·같은 KR 프록시, IP 3개씩). 405 는 JS 이전 HTTP 계층이라 WebGL·폰트 등 지문은
원인이 아니었다. 리눅스에서만 UA 플랫폼 토큰을 맥으로 치환하며, Chrome 버전은 실제 값을 유지한다.
쿠팡은 잘 통과하므로 건드리지 않았다.
2026-08-06 15:42:49 +09:00
163 changed files with 5272 additions and 887 deletions

No files matched your search

+1
View File
@@ -31,3 +31,4 @@ CLAUDE.md
/mobile.mov
.gstack/
.playwright-mcp/
Binary file not shown.
Binary file not shown.
+59 -16
View File
@@ -8,9 +8,8 @@
2) 변수 정의 — 그 금액을 지금 쓸 수 있는지 (OFFER_VARIABLES 의 계산식 + 유효조건)
3) tactic JSONB — 문장으로 알 수 없는 운영 규칙 (min_round·closing)
유효 조건을 카드가 아니라 '변수'에 붙이는 이유: 절충가가 목표가를 넘을 수 있는 것은
(직전제안+제시가)/2 라는 계산식의 성질이지 특정 카드의 성질이 아니다. 같은 변수를 쓰는
카드가 늘어도 규칙은 한 곳이고, 새 변수는 이 표에 한 줄 추가하면 코드 분기 없이 끝난다.
유효 조건은 카드가 아니라 '변수'에 붙인다 — 금액이 성립하는지는 계산식의 성질이지 카드의
성질이 아니다. 새 변수는 OFFER_VARIABLES 에 한 줄 추가하면 코드 분기 없이 끝난다.
"""
import re
@@ -32,6 +31,9 @@ OFFER_VARIABLES: Dict[str, Callable[[float, float, float, float], Optional[float
_TOKEN_RE = re.compile(r"\{([a-z_]+)\}")
# 절충 계열 변수 — 양측 사이/우리 두 값 사이의 중간을 부르는 카드. 목표가 이상이면 미발동한다.
_MID_VARIABLES = ("middle_price", "target_mid_price")
# 세션 데이터에 따라 값이 없을 수 있는 읽기 전용 변수 → 그 값을 담는 컨텍스트 키.
# 스크립트가 이런 변수를 인용하면 값이 있을 때만 카드가 나간다 — 없는데 나가면 협력사 채팅에
@@ -65,9 +67,8 @@ HOLD = CardSpec() # 스펙을 못 찾은 카드(테넌트 데모·회사 커스
def settle_ceiling(context: Dict[str, Any]) -> float:
"""이 협상에서 받아줄 수 있는 최고가 — 타결 판정선이자 카드 제안가의 상한.
견적 생성 시 세션에 박제한 done_ceiling_price(= 목표가 × (1 + 타결상한율)). 목표가를 조금
넘더라도 기존 단가보다 인하됐으면 타결시키기 위한 값이다(IMK: 기존 17,500 / 목표 16,980 /
최종 17,300 이 결렬되던 케이스). 박제가 없는 옛 세션·데모는 목표가로 폴백 — 종전 동작 유지.
견적 생성 시 세션에 박제한 done_ceiling_price(= 목표가 × (1 + 타결상한율)) — 목표가를 조금
넘더라도 기존 단가보다 인하됐으면 타결시키기 위한 값. 박제가 없으면 목표가로 폴백한다.
"""
return float(context.get("done_ceiling_price") or context.get("target_price") or 0)
@@ -75,9 +76,8 @@ def settle_ceiling(context: Dict[str, Any]) -> float:
def parse_offer_variable(script: Optional[str]) -> Optional[str]:
"""스크립트가 제시하는 제안가 변수. 없으면 None(설득 카드).
제안가 변수가 여럿이면 **마지막에 등장하는 것**이 제안가다 — 카드 문장은 배경을 먼저 깔고
(예: "당초 검토한 적정가는 {anchoring_price}원이었으나") 실제 제안을 마지막에 하기 때문이다
(예: "이에 {target_price}원으로 조정하여 제안 드립니다").
변수가 여럿이면 마지막에 등장하는 것이 제안가다 — 카드 문장은 배경을 먼저 깔고 실제 제안을
마지막에 하기 때문이다.
"""
found = [m.group(1) for m in _TOKEN_RE.finditer(script or "") if m.group(1) in OFFER_VARIABLES]
return found[-1] if found else None
@@ -115,16 +115,50 @@ def spec_from_context(context: Dict[str, Any], number: Optional[str]) -> CardSpe
)
@dataclass(frozen=True)
class Offer:
"""확정된 제안 한 건 — 금액과 그 금액을 만든 재료를 함께 들고 다닌다.
멘트 치환이 재료를 다시 계산하지 않게 하기 위한 것 — 재계산하면 그 사이 갱신된
prev_customer 를 읽어 문장이 자기모순이 된다.
"""
price: int # 협력사에게 제시할 금액(수락 시 타결가)
variable: str # 이 금액을 만든 멘트 변수
prev_customer: int # 계산에 쓴 당사 직전 제안
prev_partner: int # 계산에 쓴 협력사 제시가
def record_offer(context: Dict[str, Any], offer: Offer) -> None:
"""확정 제안을 세션에 기록한다 — 수락 판정용 금액과 멘트 치환용 재료를 한 자리에서 쓴다.
두 키를 항상 함께 써야 표시가와 타결가가 갈라지지 않으므로 기록 지점을 여기 하나로 묶는다.
"""
context["pending_counter_price"] = offer.price
context["pending_offer"] = {
"price": offer.price, "variable": offer.variable,
"prev_customer": offer.prev_customer, "prev_partner": offer.prev_partner,
}
context["prev_customer_price"] = offer.price # 갑의 최신 포지션 — 다음 라운드 계산·역행 금지 기준
def compute_offer_detail(spec: CardSpec, context: Dict[str, Any]) -> Optional[Offer]:
"""카드가 제시할 금액 + 그 계산에 쓴 재료. 쓸 수 없는 상황이면 None."""
price = int(float(context.get("input_price") or 0))
prev_customer = int(float(context.get("prev_customer_price") or context.get("anchor_price") or 0))
value = compute_offer(spec, context)
if value is None:
return None
return Offer(price=value, variable=spec.offer_variable or "", prev_customer=prev_customer, prev_partner=price)
def compute_offer(spec: CardSpec, context: Dict[str, Any]) -> Optional[int]:
"""카드가 제시할 금액. 쓸 수 없는 상황이면 None → 호출부가 카드를 건너뛴다.
변수 공통 유효조건 (전부 만족해야 발동):
· 값 ≤ 타결 상한가 — 구매자는 받아줄 수 없는 금액을 부르지 않는다. 넘으면 클램프가 아니라
**미발동**(깎아 부르면 "중간에서 만나자"면서 상한을 부르는 모순이 된다).
상한은 견적 생성 시 박제한 done_ceiling_price(목표가×(1+율)), 없으면 목표가.
· 값 ≤ 타결 상한가 — 받아줄 수 없는 금액은 부르지 않는다. 넘으면 깎지 않고 미발동
· 값 < 협력사 제시가 — 이미 더 싸게 받았는데 더 비싼 값을 부를 이유가 없다
· 값 ≥ 당사 직전 제안 — 역행 금지(IMK 논의). 16,980을 불러놓고 16,810(앵커)을 부르면 협상이
좁혀지지 않고 되돌아간다. 제안 시퀀스는 앵커→…→목표가로 단조 수렴해야 한다
· 값 ≥ 당사 직전 제안 — 역행 금지. 제안 시퀀스는 앵커→…→목표가로 단조 수렴해야 한다
"""
variable = spec.offer_variable
if not variable:
@@ -145,7 +179,16 @@ def compute_offer(spec: CardSpec, context: Dict[str, Any]) -> Optional[int]:
return None # 재료 부족(앵커 미박제·직전 제안 없음)
if value > settle_ceiling(context):
return None # 타결 상한 초과 — 받아줄 수 없는 금액이라 지금 못 쓴다
offer = int(value / 10 + 0.5) * 10 # 10원 단위 반올림 — 앵커가·목표가 산정과 표기 통일
if variable in _MID_VARIABLES and value >= target:
# 절충 계열은 목표가 미만일 때만 의미가 있다. 목표가 이상이면 "절반씩 나누자"면서 목표가를
# 부르는 꼴이라 미발동 — 목표가 제시는 목표가 카드(최후통첩)가 할 일이다.
return None
if variable in ("target_price", "anchoring_price", "anchor_price"):
# 원값 인용 변수 — 멘트엔 {target_price} 등 저장 원값이 그대로 나가므로, 반올림하면
# 표시가≠타결가 미스매치가 난다(목표가 7652 멘트 → 7650 타결). 저장값 그대로 제시.
offer = int(value)
else:
offer = int(value / 10 + 0.5) * 10 # 파생가(절충·중간) 10원 반올림 — 앵커·목표가 산정과 표기 통일
if offer >= price:
return None # 제시가가 이미 그 값 이하 → 부를 이유 없음
if prev_customer and offer < prev_customer:
@@ -173,7 +216,7 @@ def playable(spec: CardSpec, context: Dict[str, Any], *, closing_phase: bool = F
금액을 인용하는 카드(offer_variable 있음)는 그 금액을 못 부르는 상황이면 설득 폴백으로도
내보내지 않는다 — 멘트에 무효한 금액(직전 제안보다 낮은 앵커, 제시가보다 높은 목표가)이
글자로 박혀 나가 역행/모순 서사가 되기 때문(IMK 역행 논의). 설득 카드는 금액이 없으니 무관.
글자로 박혀 나가 역행/모순 서사가 되기 때문. 설득 카드는 금액이 없으니 무관.
"""
if not available(spec, context, closing_phase=closing_phase):
return False
@@ -36,26 +36,26 @@ _QUOTATION_SETTINGS = table(
)
_ITEMS = table("items", column("item_id"), column("name"), column("price"), column("purchase_price"),
column("company_id"), column("internet_lowest_price"), column("deleted"), schema="partner")
# 고객사 설정(companies.settings) — 협상 기준가로 쓸 가격 컬럼과 그 호칭을 여기서 정한다.
# 고객사 설정(companies.settings) — 협상 기준가로 쓸 가격 컬럼을 여기서 정한다.
_COMPANIES = table("companies", column("company_id"), column("settings"), column("deleted"), schema="company")
# 협상 기준가 후보: items 컬럼 ↔ 용어 카탈로그 키 ↔ 용어 미설정 시 기본값.
# 기본값은 negodata 용어 카탈로그(LABEL_CATALOG)의 base 와 같아야 한다 — 화면 라벨과
# 협상 멘트 호칭이 갈리지 않도록. 문장이 어색하면 회사가 용어 탭에서 바꾼다.
_BASELINE_PRICE = ("price", "item.price", "상품 단가")
_BASELINE_PURCHASE = ("purchase_price", "item.purchase_price", "매입가")
_BASELINE_BY_FIELD = {"price": _BASELINE_PRICE, "purchase_price": _BASELINE_PURCHASE}
# 협상 기준가 후보 컬럼. 어느 컬럼을 고르든 공급사 화면 호칭은 '공급가'로 고정한다 —
# 같은 돈을 고객사는 매입가·상품 단가 등으로 부르지만 챗은 공급사가 보는 화면이라
# 공급사 관점 용어 하나만 쓴다. 회사 용어 사전(labels)은 관리자 화면 전용.
_BASELINE_PRICE = "price"
_BASELINE_PURCHASE = "purchase_price"
_SUPPLIER_PRICE_LABEL = "공급가"
def _resolve_baseline(settings: dict) -> tuple:
"""회사 설정 → 협상 기준가로 쓸 (컬럼, 라벨키, 호칭 폴백).
def _resolve_baseline(settings: dict) -> str:
"""회사 설정 → 협상 기준가로 쓸 items 컬럼명.
1순위는 관리자가 회사 설정에서 고른 값(features.nego_baseline_field).
미설정 회사는 공급가가 기본이되, 공급가를 화면에서 감췄다면 그 회사는 공급가를 관리하지
않는다는 뜻이므로 매입가로 폴백한다 — 설정 화면이 생기기 전에 만들어진 회사를 위한 안전망."""
chosen = (settings.get("features") or {}).get("nego_baseline_field")
if chosen in _BASELINE_BY_FIELD:
return _BASELINE_BY_FIELD[chosen]
if chosen in (_BASELINE_PRICE, _BASELINE_PURCHASE):
return chosen
hidden = set(settings.get("hidden_fields") or [])
if "price" in hidden and "purchase_price" not in hidden:
return _BASELINE_PURCHASE
@@ -84,6 +84,7 @@ _NEGO_CARDS = table(
_WILD_CARDS = table(
"wild_cards",
column("wild_card_id"), column("number"), column("script"), column("tactic"), column("deleted"),
column("available"),
schema="card",
)
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
@@ -178,7 +179,7 @@ class NegoContextCRUD(INegoContextCRUD):
return ErrorType.DB_RUN_FAILED, None
async def get_item_baseline(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Tuple[int, str, dict]]:
_fallback = (0, _BASELINE_PRICE[2], {})
_fallback = (0, _SUPPLIER_PRICE_LABEL, {})
try:
# 상품 + 소속 고객사 설정 한 번에. 회사가 없어도(데이터 이상) 상품 행은 나오도록 outer join.
query = (
@@ -194,10 +195,9 @@ class NegoContextCRUD(INegoContextCRUD):
price, purchase_price, settings = rows[0]
settings = settings if isinstance(settings, dict) else {}
labels = settings.get("labels") or {}
field, label_key, label_fallback = _resolve_baseline(settings)
label = labels.get(label_key) or label_fallback
value = purchase_price if field == "purchase_price" else price
return ErrorType.SUCCESS, (int(value or 0), label, labels)
field = _resolve_baseline(settings)
value = purchase_price if field == _BASELINE_PURCHASE else price
return ErrorType.SUCCESS, (int(value or 0), _SUPPLIER_PRICE_LABEL, labels)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, _fallback
@@ -375,6 +375,8 @@ class NegoContextCRUD(INegoContextCRUD):
_VERSION_WILD_CARDS.c.version_id == version_id,
_VERSION_WILD_CARDS.c.deleted == False, # noqa: E712
_WILD_CARDS.c.deleted == False, # noqa: E712
# 협상 적용 여부(카드 설정 '적용 대기(수동)') — 꺼진 카드는 견적에 담겨 있어도 발동 금지
_WILD_CARDS.c.available == True, # noqa: E712
)
.order_by(_VERSION_WILD_CARDS.c.created_at)
)
+55 -42
View File
@@ -11,11 +11,15 @@ from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from negotiation.cards.domain.tactics import (
available, compute_offer, is_played, mark_played, playable, settle_ceiling, spec_from_context,
OFFER_VARIABLES, Offer, available, compute_offer_detail, is_played, mark_played, playable,
record_offer, settle_ceiling, spec_from_context,
)
from negotiation.chat.service.script_repository import ScriptRepository
MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config negotiation.max_counter_rounds)
# 멘트에 찍히는 파생 가격 — 값이 다른 값에서 계산돼 나오는 것들(원값 인용 target/anchor 는 제외).
_DERIVED_PRICE_VARIABLES = ("target_mid_price", "middle_price")
_PRICE_MODES = ("price",)
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
@@ -55,10 +59,10 @@ _SCRIPT_LABELS = {
"label_delivery_type_2": ("delivery_type.2", "지정택배배송"),
"label_delivery_type_3": ("delivery_type.3", "픽업배송"),
"label_product": ("item.name", "상품명"),
# 협상 기준가 호칭의 최후 폴백. 실제 값은 loader 가 회사 설정에서 정해 컨텍스트에 박제하고,
# 이 값은 DB 컨텍스트가 없는 데모/직접호출 경로에서만 쓰인다.
"label_item_price": ("item.price", "상품 단가"),
}
# 협상 기준가 호칭 — 공급사 화면 고정 용어. 회사 용어 사전(labels)을 타지 않는다(그건 관리자 화면 전용).
# 실제 값은 loader 가 컨텍스트에 박제하고, DB 컨텍스트가 없는 데모/직접호출 경로만 이 폴백을 쓴다.
_SUPPLIER_PRICE_LABEL = "공급가"
# 조사 자동 보정: 토큰 뒤에 조사가 붙는 자리는 {label_supplier_를} 처럼 대표형을 적는다.
# 회사가 바꾼 용어의 받침을 예측할 수 없어 스크립트에 조사를 고정할 수 없다("협력사를"/"공급업체을").
_JOSA = {"은": ("은", "는"), "는": ("은", "는"), "이": ("이", "가"), "가": ("이", "가"),
@@ -131,8 +135,9 @@ class ChatEngine:
if price is None:
return self._error(session, "가격을 숫자로 입력해 주세요.")
session.context["input_price"] = price
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터 폐기.
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터·그 재료 폐기.
session.context.pop("pending_counter_price", None)
session.context.pop("pending_offer", None)
session.context["prev_partner_price"] = price
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
session.context.setdefault("first_offer_price", price)
@@ -150,6 +155,7 @@ class ChatEngine:
# 원 제시가 수락 종결 — 는 카운터를 버리고 기존 input_price 로 타결한다.)
if mode in _CHOICE_MODES and nxt in _SUCCESS_STEPS:
pending = session.context.pop("pending_counter_price", None)
session.context.pop("pending_offer", None)
if pending and user_input in _ACCEPT_INPUTS:
session.context["input_price"] = float(pending)
return self._render(session, nxt)
@@ -240,7 +246,7 @@ class ChatEngine:
)
if exhausted:
# 타결선은 목표가가 아니라 타결 상한가(견적 생성 시 박제) — 목표가를 넘어도
# 상한 이내면 타결한다(IMK: 기존 단가보다 인하됐는데 결렬되던 케이스).
# 상한 이내면 타결한다.
ceiling = settle_ceiling(ctx)
if not ctx.get("closing_played"):
ctx["force_closing"] = True
@@ -255,12 +261,8 @@ class ChatEngine:
def _pick_wildcard(self, session: ChatSession) -> str:
"""앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
견적에서 실제 선택한 와일드카드(중간값 절충·목표가 선제안 등)와 매핑되지 않은 채
'와일드카드를 하나라도 골랐으면' 조건만으로 발동해, 선택하지도 않은 재원부족 멘트가
노출되는 오작동이 있었다.
앵커가 이하로 유도한다. 그 외 구간은 견적에서 선택한 와일드카드의 전술로 카운터하고,
낼 카드가 없으면 일반 가격협상(카드 플레이)으로 돌린다.
"""
ctx = session.context
price = ctx.get("input_price", 0)
@@ -268,15 +270,16 @@ class ChatEngine:
target = ctx.get("target_price", 0)
if anchor > 0 and price <= anchor * self.rules.wildcard_1pct_ratio:
offer_1pct = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 — 10원 반올림(앵커·카운터와 통일)
# 제안가 공통 유효조건(≤목표가 · <제시가)은 시스템 1% 카드에도 동일하게 건다.
# 기본 앵커 밴드에선 수학적으로 항상 통과하지만, 앵커율 0 등 극단 데이터를 방어한다.
if 0 < offer_1pct < price and (target <= 0 or offer_1pct <= target):
# 제안가 공통 유효조건(≤목표가 · <제시가 · 직전 당사 제안 이상=역행 금지)은 시스템 1% 카드에도
# 동일하게 건다. 기본 앵커 밴드에선 수학적으로 항상 통과하지만 극단 데이터를 방어한다.
prev_customer = ctx.get("prev_customer_price") or 0
if 0 < offer_1pct < price and (target <= 0 or offer_1pct <= target) and offer_1pct >= prev_customer:
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
ctx["wildcard_used"] = True
ctx["offer_1pct"] = offer_1pct
ctx["pending_counter_price"] = offer_1pct # 수락 시 이 가격으로 타결
ctx["prev_customer_price"] = offer_1pct # 갑의 최신 포지션 — 이후 절충가 계산 기준
record_offer(ctx, Offer(price=offer_1pct, variable="offer_1pct",
prev_customer=int(prev_customer or anchor), prev_partner=int(price)))
return "wild_card_1pct"
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
# (구현 전에는 이 구간이 일반 가격협상으로 회귀해 선택형 WC 가 영영 발동하지 않던 갭.)
@@ -288,11 +291,10 @@ class ChatEngine:
# 이미 쓴 카드도 제외(같은 멘트 반복 방지).
if not available(spec, ctx) or is_played(ctx, number):
continue
offer = compute_offer(spec, ctx)
offer = compute_offer_detail(spec, ctx)
if offer is not None:
ctx["wildcard_used"] = True
ctx["pending_counter_price"] = offer
ctx["prev_customer_price"] = offer # 갑의 최신 포지션 — "당사 제안 ○원" 멘트가 실제 이력과 일치
record_offer(ctx, offer)
ctx["active_wild_card_number"] = number
mark_played(ctx, number)
return "wild_card_dynamic"
@@ -320,6 +322,11 @@ class ChatEngine:
out[token] = word
for form in ("는", "가", "를", "와"):
out[f"{token}_{form}"] = _josa(word, form)
# 기준가 호칭은 회사 용어가 아니라 공급사 관점 고정 — loader 박제값(없으면 '공급가').
price_word = str(ctx.get("item_price_label") or _SUPPLIER_PRICE_LABEL)
out["label_item_price"] = price_word
for form in ("는", "가", "를", "와"):
out[f"label_item_price_{form}"] = _josa(price_word, form)
# 카드 에디터 카탈로그의 협력사명/상품명(partner_name·product_name) 치환.
if ctx.get("partner_name"):
out["partner_name"] = str(ctx["partner_name"])
@@ -336,32 +343,38 @@ class ChatEngine:
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.OFFER_VARIABLES 산식과 동일 정의.
anchor = ctx.get("anchor_price") or 0
target = ctx.get("target_price") or 0
if "input_price" in ctx:
out["prev_partner_price"] = int(ctx.get("prev_partner_price") or ctx["input_price"])
prev_customer = ctx.get("prev_customer_price") or anchor
# 표시 기준값 — 제안이 확정된 턴이면 그 계산에 쓴 재료(pending_offer)를 쓴다.
# prev_customer_price 는 확정 즉시 새 제안가로 갱신되므로, 그대로 읽으면 멘트가
# "당사 제안과 귀사 제안의 절반이 당사 제안" 같은 자기모순이 된다.
pending_offer = ctx.get("pending_offer") or {}
prev_customer = int(pending_offer.get("prev_customer") or ctx.get("prev_customer_price") or anchor or 0)
partner_price = int(pending_offer.get("prev_partner") or ctx.get("prev_partner_price") or ctx.get("input_price") or 0)
offer_price = int(pending_offer.get("price") or ctx.get("pending_counter_price") or 0)
offer_variable = pending_offer.get("variable") or ""
if prev_customer:
out["prev_customer_price"] = int(prev_customer)
if anchor and target:
out["target_mid_price"] = int(round((anchor + target) / 2))
if prev_customer and "input_price" in ctx:
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
if ctx.get("pending_counter_price"):
# 카운터 제시 중: 멘트에 보이는 제시가와 수락 시 타결가(pending)를 반드시 일치시킨다.
# 절충/중간 변수(middle_price·target_mid_price)는 vars_for 재계산 값이 compute_offer 의
# target 클램프·prev_customer 갱신과 어긋나, 멘트엔 1,740,000 이 보이는데 실제로는
# 1,700,000 으로 타결되던 버그(표시가≠투찰가)가 있었다. pending 은 이 시점 유일한 '제안가'이므로
# 세 변수 모두 pending 으로 고정한다(카운터 제시 턴에만 적용 — 비-카운터 렌더는 원 계산값 유지).
pending_i = int(ctx["pending_counter_price"])
out["counter_price"] = pending_i
out["middle_price"] = pending_i
out["target_mid_price"] = pending_i
out["prev_customer_price"] = prev_customer
if partner_price:
out["prev_partner_price"] = partner_price
if offer_price:
out["counter_price"] = offer_price
# 파생 가격(절충가·중간가) — 제안가로 확정된 변수는 그 금액을 그대로 쓴다(멘트에 보이는 금액과
# 수락 시 타결가는 항상 같아야 한다). 나머지는 참고 인용이므로 tactics 산식으로 채운다.
# 산식을 여기 복사해 두면 갱신 시점 차이로 표시가와 제안가가 갈라지므로 정의를 호출만 한다.
# 어느 변수가 제안가인지 모르는 진행 중 세션(구버전 기록)은 종전대로 전부 제안가로 고정한다.
for name in _DERIVED_PRICE_VARIABLES:
if offer_price and (name == offer_variable or not offer_variable):
out[name] = offer_price
continue
value = OFFER_VARIABLES[name](target, anchor, partner_price, prev_customer)
if value:
out[name] = int(value / 10 + 0.5) * 10 # 10원 반올림 — compute_offer 와 동일
# 인하율 = (협상 기준가 - 제시가) / 기준가 * 100. 기준가 없으면 미표시(0.0).
# 제시가가 기준가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
# 문구는 discount_phrase 로 별도 제공한다(가격협상_확인 멘트가 사용).
# 기준가 호칭(공급가/매입가/회사 라벨)은 회사 설정에서 온다 — loader 가 박제한 값.
# 기준가 호칭은 공급사 화면 고정 용어('공급가') — loader 가 박제한 값.
base = ctx.get("item_price") or 0
label = ctx.get("item_price_label") or _SCRIPT_LABELS["label_item_price"][1]
label = ctx.get("item_price_label") or _SUPPLIER_PRICE_LABEL
if base > 1 and "input_price" in ctx:
rate = ((base - ctx["input_price"]) / base) * 100
out["discount_rate"] = f"{max(0.0, rate):.1f}"
@@ -390,8 +403,8 @@ class ChatEngine:
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
# 가드레일(최후 방어선): 구매자 대리는 타결 상한가를 넘겨 타결하지 않는다.
# 상한 = 견적 생성 시 박제한 done_ceiling_price(목표가×(1+타결상한율)), 미박제면 목표가.
# 목표가를 조금 넘어도 상한 이내면 타결이 정상이므로(IMK: 기존 단가보다 인하됐는데
# 결렬되던 케이스) 여기서 뒤집으면 안 된다. 상한까지 넘은 경우만 결렬로 강제 전환한다.
# 목표가를 조금 넘어도 상한 이내면 타결이 정상이므로 여기서 뒤집지 않는다.
# 상한까지 넘은 경우만 결렬로 강제 전환한다.
if step_key in _SUCCESS_STEPS and self.rq_type == "재협상":
ctx = session.context
ceiling = settle_ceiling(ctx)
+19 -14
View File
@@ -13,7 +13,9 @@ from common.enums import DBType, ErrorType
from common.database.db_session_manager import DB_SESSION_MNG
from common.logger import LOG
from config.server_configs import agent_config
from negotiation.cards.domain.tactics import available, compute_offer, is_played, mark_played, playable, spec_from_context
from negotiation.cards.domain.tactics import (
Offer, available, compute_offer_detail, is_played, mark_played, playable, record_offer, spec_from_context,
)
from negotiation.chat.service.chat_engine import (
_CHOICE_MODES, _PRICE_MODES, ChatEngine, ChatSession, StepView,
)
@@ -41,7 +43,7 @@ _DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_reven
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
_DEFAULT_PARTNER_NAME = "귀사" # 협력사명 — suppliers.name 미기재/데모 시 폴백(카드 {partner_name})
_DEFAULT_PRODUCT_NAME = "본 상품" # 상품명 — items.name 미기재/데모 시 폴백(카드 {product_name})
_DEFAULT_ITEM_PRICE_LABEL = "상품 단가" # 협상 기준가 호칭 — DB 컨텍스트 없는 데모/직접호출 경로 폴백
_DEFAULT_ITEM_PRICE_LABEL = "공급가" # 협상 기준가 호칭(공급사 화면 고정 용어) — DB 컨텍스트 없는 데모/직접호출 경로 폴백
# (negodata 용어 카탈로그 item.price 의 base 와 같아야 표기가 갈리지 않는다)
@@ -309,10 +311,10 @@ class ChatService:
# 협력사가 수락하면 이 가격으로 즉시 타결된다(chat_engine 의 수락 메커니즘).
# 유효조건(≤목표가 · <제시가) 미달이면 None → 금액 없이 설득 멘트만 나간다(HOLD 강등).
spec = spec_from_context(session.context, card_id)
counter = compute_offer(spec, session.context) if available(spec, session.context) else None
if counter is not None:
session.context["pending_counter_price"] = counter
session.context["prev_customer_price"] = counter # 갑의 최신 포지션(절충가 계산 기준)
offer = compute_offer_detail(spec, session.context) if available(spec, session.context) else None
counter = offer.price if offer else None
if offer is not None:
record_offer(session.context, offer)
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
@@ -369,26 +371,29 @@ class ChatService:
ctx["closing_played"] = True
# 선택 와일드카드 중 종결 전용 카드(closing) — 이미 쓴 카드는 건너뛰고(같은 멘트 반복 방지),
# 제안가 유효조건(≤목표가 · <제시가) 미달 카드도 건너뛴다(예: 절충가가 목표가 초과 → 미발동).
closing_number, counter = None, None
closing_number, closing_offer = None, None
for n in (ctx.get("selected_wild_card_numbers") or []):
n = str(n)
spec = spec_from_context(ctx, n)
if not available(spec, ctx, closing_phase=True) or is_played(ctx, n):
continue
offer = compute_offer(spec, ctx)
offer = compute_offer_detail(spec, ctx)
if offer is not None:
closing_number, counter = n, offer
closing_number, closing_offer = n, offer
break
if counter is None:
if closing_offer is None:
# 폴백 최후통첩: 목표가 제시 (여기 도달 = 제시가 > target 이므로 항상 유효한 카운터).
closing_number = None
target = int(ctx.get("target_price") or 0)
counter = target if 0 < target < ctx.get("input_price", 0) else None
if counter is None:
price = int(ctx.get("input_price") or 0)
if 0 < target < price:
closing_offer = Offer(price=target, variable="target_price",
prev_customer=int(ctx.get("prev_customer_price") or ctx.get("anchor_price") or 0),
prev_partner=price)
if closing_offer is None:
return # 컨텍스트 이상 — 기존 가격협상 스텝 그대로(재제안 요구)
mark_played(ctx, closing_number) # None(폴백 최후통첩)이면 no-op
ctx["pending_counter_price"] = counter
ctx["prev_customer_price"] = counter
record_offer(ctx, closing_offer)
template = None
if closing_number:
+4 -3
View File
@@ -191,8 +191,9 @@ async def test_loader_with_crud_double(db_engine):
return ErrorType.SUCCESS, (2, 50000, None, 52500, uuid.uuid4(), uuid.uuid4(), uuid.uuid4())
async def get_item_baseline(self, cdb, item_id):
# 기준가를 매입가로 고른 회사 + 거래상대 호칭을 '공급업체'로 바꾼 용어 사전
return ErrorType.SUCCESS, (7000, "매입가", {"supplier": "공급업체"})
# 기준가를 매입가로 고른 회사 + 거래상대 호칭을 '공급업체'로 바꾼 용어 사전.
# 호칭은 crud 가 어떤 회사든 '공급가'(공급사 화면 고정 용어)로 내려준다.
return ErrorType.SUCCESS, (7000, "공급가", {"supplier": "공급업체"})
async def get_item_lowest_price(self, cdb, item_id):
return ErrorType.SUCCESS, 6300 # 인터넷 최저가(items.internet_lowest_price)
@@ -233,7 +234,7 @@ async def test_loader_with_crud_double(db_engine):
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
assert ctx.done_ceiling_price == 52500 # 타결 상한가 박제값(목표가 +5%)
assert ctx.item_price == 7000
assert ctx.item_price_label == "매입가" # 기준가 호칭이 멘트까지 전달되는지
assert ctx.item_price_label == "공급가" # 기준가 호칭이 멘트까지 전달되는지
assert ctx.labels == {"supplier": "공급업체"} # 회사 용어 사전이 스크립트 토큰용으로 실리는지
assert ctx.internet_lowest_price == 6300 # 인터넷 최저가 로드 확인
assert ctx.card_count == 3 # 협상카드 사용 횟수 상한 로드 확인
+37 -23
View File
@@ -1,18 +1,33 @@
from abc import ABC, abstractmethod
from typing import Tuple
from typing import Optional, Tuple
from sqlalchemy import case, cast, func, nulls_last, or_, select, text, update
from sqlalchemy import and_, case, cast, func, nulls_last, or_, select, text, update
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import items, quotations, sessions
from common.database.model.models import chats, items, quotations, sessions
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
from common.logger import LOG
# 협상 세션 CRUD. 목록은 세션(negotiation) ⨝ 상품(partner) ⨝ 견적(quotation) 조인으로 만든다.
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
def _effective_status():
"""표시용 세션 상태. 견적이 마감됐거나 마감시간이 지났으면 협상생성(1)은 더 참여할 수 없으므로 미참여(4)로 본다.
참여/채팅진입이 진입 시점에 하는 전이(negotiation_service._load_actionable_session, chat_service.init)와 같은 규칙을
목록에서는 쓰기 없이 파생으로만 맞춘다. 마감 일괄정리 이후에 만들어진 세션도 '협상 대기'로 남지 않는다.
"""
ended = or_(quotations.status == QuotationStatus.CLOSED.value, quotations.end_time < func.now())
return case(
(and_(sessions.status == SessionStatus.CREATED.value, ended), SessionStatus.NOT_PARTICIPATED.value),
else_=sessions.status,
)
class ISessionCRUD(ABC):
@abstractmethod
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
@@ -39,7 +54,9 @@ class ISessionCRUD(ABC):
pass
@abstractmethod
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
async def update_session_reject(
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
) -> ErrorType:
pass
@abstractmethod
@@ -47,19 +64,6 @@ class ISessionCRUD(ABC):
pass
@abstractmethod
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
try:
query = select(func.max(quotations.round)).where(quotations.number == number, quotations.deleted == False) # noqa: E712
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, 0
top = rows[0][0] if rows and rows[0] else None
return ErrorType.SUCCESS, int(top or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
pass
@@ -73,7 +77,8 @@ class SessionCRUD(ISessionCRUD):
def __filters(supplier_id, status, qt_type, keyword=None, result=None):
conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712
if status is not None:
conds.append(sessions.status == status)
# 표시 상태로 필터 — 탭/KPI 카운트가 목록 배지와 어긋나지 않게 파생값을 그대로 쓴다.
conds.append(_effective_status() == status)
if qt_type is not None:
conds.append(sessions.qt_type == qt_type)
# 검색: 견적번호·상품명·상품코드 부분일치(대소문자 무시). items 는 목록/카운트 둘 다 조인돼 있다.
@@ -113,7 +118,7 @@ class SessionCRUD(ISessionCRUD):
else:
# 그룹별로 정렬 방향이 달라, case 로 '자기 그룹 행만 end_time' 을 갖는 키를 만들고
# 반대 그룹은 NULL 로 눌러 간섭을 없앤다. status_rank 가 1차 키라 그룹 경계는 항상 유지.
actionable = sessions.status.in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
actionable = _effective_status().in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
status_rank = case((actionable, 0), else_=1)
action_order = case((actionable, quotations.end_time), else_=None).asc()
done_order = case((~actionable, quotations.end_time), else_=None).desc()
@@ -122,7 +127,7 @@ class SessionCRUD(ISessionCRUD):
query = (
select(
sessions.session_id,
sessions.status,
_effective_status(), # 마감 후 남은 협상생성은 미참여로 내린다
sessions.qt_type,
sessions.qt_number,
quotations.end_time, # qt_end_time = 견적 마감 시각
@@ -136,6 +141,8 @@ class SessionCRUD(ISessionCRUD):
quotations.round,
quotations.preferred_sp_id, # 낙찰자(공급사) — 나와 같으면 낙찰, 다르면 미낙찰
sessions.supplier_id, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
# 대화 이력 유무 — 종료된 협상의 '결과 보기'(열람) 버튼을 띄울지 판단용. 열 게 없으면 프론트가 감춘다.
select(1).where(chats.session_id == sessions.session_id, chats.deleted == False).exists(), # noqa: E712
)
.join(items, items.item_id == sessions.item_id)
.join(quotations, quotations.qt_id == sessions.quotation_id)
@@ -212,12 +219,18 @@ class SessionCRUD(ISessionCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
async def update_session_reject(
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
) -> ErrorType:
try:
values = {"status": status, "reject_reason": reject_reason}
# 공급 희망 가격은 채팅 중 거부에서만 들어온다 — 목록 거부는 가격 없이 사유만 남긴다.
if reject_price is not None:
values["reject_price"] = reject_price
query = (
update(sessions)
.where(sessions.session_id == session_id)
.values(status=status, reject_reason=reject_reason)
.values(**values)
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
@@ -231,7 +244,8 @@ class SessionCRUD(ISessionCRUD):
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, 0
top = rows[0][0] if rows and rows[0] else None
# 단일 컬럼 select 는 scalars() 로 내려와 rows 가 값 리스트다(행 튜플이 아님).
top = rows[0] if rows else None
return ErrorType.SUCCESS, int(top or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
-1
View File
@@ -72,5 +72,4 @@ class Res_HidePopup(Res_WebPacketProtocol):
class Res_SessionBranding(Res_WebPacketProtocol):
service_name: str = Field("", description="회사 서비스명(companies.settings.branding.service_name). 미설정 시 빈 값")
logo_url: str = Field("", description="회사 로고 URL")
primary_color: str = Field("", description="브랜드 색상(hex)")
helpdesk: list = Field(default_factory=list, description="헬프데스크 연락처 줄 목록(companies.settings.branding.helpdesk). 한 줄 = 담당자 한 명")
@@ -21,6 +21,7 @@ class ListItem(WebPacketProtocol):
renegotiation_status: int = Field(0, description="현재 재협상 요청 상태(RenegotiationStatus). 요청 이력이 없으면 0")
renegotiation_memo: str = Field("", description="담당자 심사 메모(반려 사유). 없으면 빈 문자열")
result: int = Field(0, description="공급사 관점 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰, 재협상 대상)")
has_chat: bool = Field(False, description="대화 이력 존재 여부 — 종료된 협상(미참여·거부)의 '결과 보기' 노출 판단용")
class Res_SessionList(Res_WebPacketProtocol):
@@ -36,6 +37,8 @@ class Res_Participate(Res_WebPacketProtocol):
class Req_Reject(WebPacketProtocol):
reject_reason: str = Field("", max_length=255, description="거부 사유 (단종/품절 프리셋 라벨 또는 직접 입력)")
reject_price: Optional[int] = Field(None, description="공급 희망 가격(원). 채팅 중 거부에서만 들어온다 — 목록 거부엔 없음")
opinion: Optional[str] = Field(None, max_length=255, description="추가 의견 — sessions.custom.opinion 에 병합")
class Res_Reject(Res_WebPacketProtocol):
+6 -2
View File
@@ -62,7 +62,7 @@ async def participate(
path="/sessions/{session_id}/reject",
response_model=Res_Reject,
summary="협상 거부",
description="세션 참여를 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유를 저장.",
description="세션 참여를 거부하거나 진행 중인 협상을 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유·공급 희망 가격·의견을 저장.",
)
async def reject(
session_id: str = Path(description="대상 협상 세션 uuid"),
@@ -71,7 +71,11 @@ async def reject(
credentials: HTTPAuthorizationCredentials = Depends(security),
service: NegotiationService = Depends(),
):
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
return RemoveNoneResponse(
await service.reject(
user_info, credentials.credentials, session_id, req.reject_reason, req.reject_price, req.opinion,
)
)
@router.post(
-1
View File
@@ -279,7 +279,6 @@ class AuthService:
branding = branding or {}
res.service_name = branding.get("service_name") or ""
res.logo_url = branding.get("logo_url") or ""
res.primary_color = branding.get("primary_color") or ""
res.helpdesk = branding.get("helpdesk") or []
return res
+9 -8
View File
@@ -227,11 +227,8 @@ class ChatService:
)
sess.status = SessionStatus.NOT_PARTICIPATED.value
# 미참여/협상거부 상태는 진입(열람) 불가 (participate/reject 와 동일 규칙).
# 위 마감 변환으로 미참여가 된 세션도 여기서 함께 막힌다.
if sess.status in (SessionStatus.NOT_PARTICIPATED.value, SessionStatus.REJECTED.value):
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
return res
# 미참여/협상거부 세션도 '결과 보기'로 지난 대화를 열람할 수 있다(중간 이탈·거부로 끝난 건).
# 대화 재개는 send() 가 협상중(2)만 허용하므로 여기서 막지 않아도 읽기 전용이다.
await self._ensure_in_progress(sess, quote)
@@ -262,14 +259,18 @@ class ChatService:
)
res.labels = (settings.get("labels") or {}) if _e == ErrorType.SUCCESS and settings else {}
# 회사가 VAT(vat_yn)를 관리하지 않으면(hidden_fields) 협상 화면 VAT 표기를 숨긴다(값 null → 프론트 라벨 생략).
_hidden = (settings.get("hidden_fields") or []) if _e == ErrorType.SUCCESS and settings else []
if "vat_yn" in _hidden:
_features = (settings.get("features") or {}) if _e == ErrorType.SUCCESS and settings else {}
# VAT 표기 — 부가세 전체 통일 회사(features.vat_mode)는 상품 잔존값과 무관하게 'VAT 별도' 고정(False).
# 상품별 관리 회사가 vat_yn 을 숨겼으면(구 방식) 표기 자체를 생략한다(값 null → 프론트 라벨 생략).
if _features.get("vat_mode") == "unified_excluded":
res.item_vat_yn = False
elif "vat_yn" in _hidden:
res.item_vat_yn = None
# 협상 기준가 — 회사 설정에서 고른 가격 컬럼(features.nego_baseline_field).
# agent 의 인하율 멘트(nego_context_crud._resolve_baseline)와 같은 규칙이어야 화면과 멘트가 어긋나지 않는다.
_features = (settings.get("features") or {}) if _e == ErrorType.SUCCESS and settings else {}
_baseline = _features.get("nego_baseline_field")
if _baseline not in ("price", "purchase_price"):
# 미설정 회사 폴백 — 공급가를 감췄으면 그 회사는 공급가를 관리하지 않는다는 뜻.
+19 -6
View File
@@ -1,5 +1,6 @@
import uuid
from datetime import datetime, timezone
from typing import Optional
from fastapi import Depends
@@ -182,6 +183,7 @@ class NegotiationService:
renegotiation_status=status,
renegotiation_memo=renego.get("memo") or "",
result=NegotiationService._to_result(r[10], r[11], r[13], r[14]),
has_chat=bool(r[15]),
)
@staticmethod
@@ -434,7 +436,10 @@ class NegotiationService:
res.session_id = str(sess.session_id)
return res
async def reject(self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str) -> Res_Reject:
async def reject(
self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str,
reject_price: Optional[int] = None, opinion: Optional[str] = None,
) -> Res_Reject:
res = Res_Reject()
# 거부 사유 필수
@@ -454,11 +459,19 @@ class NegotiationService:
res.result.SetResult(err_type)
return res
# 거부 처리 — 세션을 협상거부로 전이하고 사유 저장
err_type = await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.session_crud.update_session_reject(s, sess.session_id, SessionStatus.REJECTED.value, reason)],
)
# 거부 처리 — 세션을 협상거부로 전이하고 사유·공급 희망 가격 저장.
# 의견은 부가정보와 같은 custom 컬럼이라 병합(덮어쓰기 금지) — 채팅 결렬 폼과 같은 자리.
funcs = [
lambda s: self.session_crud.update_session_reject(
s, sess.session_id, SessionStatus.REJECTED.value, reason, reject_price,
)
]
note = (opinion or "").strip()[:255]
if note:
funcs.append(
lambda s: self.session_crud.merge_session_custom(s, sess.session_id, sess.supplier_id, {"opinion": note})
)
err_type = await DB_SESSION_MNG.execute_lambda_run([sessions.DBType()], funcs)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
+39 -5
View File
@@ -226,6 +226,35 @@ async def test_chat_init_forbidden_other_supplier(client, chat_seed):
assert body["result"]["code"] == 1300 # NEGO_FORBIDDEN
async def test_chat_init_vat_mode_unified_shows_excluded(client, chat_seed, db_engine):
"""검증: 부가세 전체 통일 회사(features.vat_mode=unified_excluded)의 세션 채팅 init.
기대결과: 상품에 vat_yn=true 잔존값이 있어도 item_vat_yn=False — 프론트가 'VAT별도'로 고정 표기."""
import json
company_id = uuid.uuid4()
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO company.companies (company_id, name, status, settings) VALUES (:c, :n, 1, CAST(:s AS JSONB))"),
{"c": company_id, "n": f"{MARK}VAT통일사", "s": json.dumps({"features": {"vat_mode": "unified_excluded"}})},
)
await conn.execute(
text("UPDATE partner.suppliers SET company_id = :c WHERE supplier_id = :sid"),
{"c": company_id, "sid": chat_seed["supplier_id"]},
)
await conn.execute(
text("UPDATE partner.items SET vat_yn = true WHERE item_id = (SELECT item_id FROM negotiation.sessions WHERE session_id = :s)"),
{"s": chat_seed["sids"]["P"]},
)
try:
token = await _login_token(client)
body = (await _init(client, token, chat_seed["sids"]["P"])).json()
assert body["result"]["success"] is True
assert body["item_vat_yn"] is False
finally:
async with db_engine.begin() as conn:
await conn.execute(text("DELETE FROM company.companies WHERE company_id = :c"), {"c": company_id})
# ---- messages (오프닝 seed) -------------------------------------------------
async def test_messages_seeds_opening(client, chat_seed):
token = await _login_token(client)
@@ -351,23 +380,28 @@ async def test_send_blocked_when_prev_turn_pending(client, chat_seed, db_engine)
async def test_init_marks_expired_created_as_not_participated(client, chat_seed, db_engine):
"""검증: 마감시간이 지난 협상생성 세션으로 채팅 진입.
기대결과: DB 상태가 미참여(4)로 정리되고, init 자체는 열람용으로 성공한다."""
token = await _login_token(client)
sid, qid = chat_seed["sids"]["C"], chat_seed["qids"]["C"] # 협상생성(1)
async with db_engine.begin() as conn:
await conn.execute(text("UPDATE quotation.quotations SET end_time = now() - make_interval(hours => 1) WHERE qt_id = :qid"), {"qid": qid})
body = (await _init(client, token, sid)).json()
# 마감된 협상생성은 DB 상 미참여로 정리되고, 미참여는 진입 불가라 init 은 에러로 막는다.
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE
assert await _session_status(db_engine, sid) == 4 # DB 는 미참여로 전이됨
assert body["result"]["success"] is True
assert body["session_status"] == 4
assert await _session_status(db_engine, sid) == 4 # DB 도 미참여로 전이
async def test_init_blocks_rejected_session(client, chat_seed, db_engine):
async def test_init_allows_viewing_rejected_session(client, chat_seed, db_engine):
"""검증: 협상거부(5)로 끝난 세션에 '결과 보기'로 재진입.
기대결과: init 성공(열람 허용) — 대화 재개는 send 가 협상중만 허용해 막는다."""
token = await _login_token(client)
sid = chat_seed["sids"]["P"]
async with db_engine.begin() as conn:
await conn.execute(text("UPDATE negotiation.sessions SET status = 5 WHERE session_id = :sid"), {"sid": sid}) # 협상거부
body = (await _init(client, token, sid)).json()
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE — 거부 세션 진입 차단
assert body["result"]["success"] is True and body["session_status"] == 5
assert (await _send(client, token, sid, "네")).json()["result"]["code"] == 1400 # CHAT_NOT_IN_PROGRESS
# ---- 순수 헬퍼 단위 테스트 (DB 불필요, ChatService @staticmethod) ----------
+128 -25
View File
@@ -16,6 +16,35 @@ TEST_SUPPLIER_NAME = "파이테스트협상공급사"
MARK = "PYTESTNEGO-" # 시드 식별용 prefix (item code / qt number)
async def _seed_case(conn, code, sess_st, qt_type, hrs, quote_st, sup):
"""상품·견적·세션 1세트 시드. 코드/견적번호에 MARK prefix 를 달아 cleanup 이 함께 지운다.
hrs 는 마감(quotation.end_time)까지의 시간 — 음수면 이미 마감시간이 지난 건. 반환: (session_id, qt_id)."""
item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
await conn.execute(
text(
"INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')"
),
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"},
)
await conn.execute(
text(
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time) "
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, :tp, :st, now(), now() + make_interval(hours => :hrs))"
),
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "tp": qt_type, "st": quote_st, "hrs": hrs},
)
await conn.execute(
text(
"INSERT INTO negotiation.sessions "
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, target_price, status, end_time) "
"VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, :qtt, 100000, :st, now())"
),
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st},
)
return session_id, qt_id
@pytest_asyncio.fixture
async def nego_seed(db_engine):
"""공급사 + 유저 + 세션/견적 3건(본인) + 1건(타 공급사) 시드. 세션/견적 id 를 반환."""
@@ -33,6 +62,11 @@ async def nego_seed(db_engine):
sids, qids = {}, {}
async def _cleanup(conn):
# 대화는 세션보다 먼저 지운다(세션이 사라지면 대상을 못 고른다).
await conn.execute(text(
f"DELETE FROM negotiation.chats WHERE session_id IN "
f"(SELECT session_id FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%')"
))
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
@@ -52,31 +86,9 @@ async def nego_seed(db_engine):
),
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
)
for code, sess_st, qt_type, hrs, quote_st, sup in specs:
item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
sids[code], qids[code] = session_id, qt_id
await conn.execute(
text(
"INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')"
),
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"},
)
await conn.execute(
text(
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time) "
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, :tp, :st, now(), now() + make_interval(hours => :hrs))"
),
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "tp": qt_type, "st": quote_st, "hrs": hrs},
)
await conn.execute(
text(
"INSERT INTO negotiation.sessions "
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, target_price, status, end_time) "
"VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, :qtt, 100000, :st, now())"
),
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st},
)
for spec in specs:
code = spec[0]
sids[code], qids[code] = await _seed_case(conn, *spec)
yield {"supplier_id": supplier_id, "sids": sids, "qids": qids}
@@ -141,6 +153,63 @@ async def test_list_filter_status(client, nego_seed):
assert body["total"] == 1 and body["items"][0]["item_code"] == f"{MARK}B"
async def test_list_shows_closed_quotation_created_session_as_not_participated(client, db_engine, nego_seed):
"""검증: 견적이 마감(3)된 뒤에도 세션이 협상생성(1)으로 남아 있는 건(마감 일괄정리 이후 생성 등).
기대결과: 목록 상태는 미참여(4) — '협상 대기'로 새지 않고, status=1 필터에서도 빠지고 status=4 필터에 잡힌다."""
async with db_engine.begin() as conn:
await _seed_case(conn, "CLOSED1", 1, 2, -1, 3, nego_seed["supplier_id"])
token = await _login_token(client)
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CLOSED1")
assert listed["session_status"] == 4
waiting = (await _list(client, token, status=1)).json()
assert waiting["total"] == 1 and {i["item_code"] for i in waiting["items"]} == {f"{MARK}A"}
assert f"{MARK}CLOSED1" in {i["item_code"] for i in (await _list(client, token, status=4)).json()["items"]}
async def test_list_shows_deadline_passed_created_session_as_not_participated(client, db_engine, nego_seed):
"""검증: 견적은 아직 진행중(2)인데 마감시간(end_time)만 지난 협상생성 세션.
기대결과: 미참여(4) — 참여/입장이 막히는 건이라 목록도 같은 상태로 보인다(DB 값은 그대로)."""
async with db_engine.begin() as conn:
session_id, _ = await _seed_case(conn, "OVERDUE", 1, 2, -3, 2, nego_seed["supplier_id"])
token = await _login_token(client)
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}OVERDUE")
assert listed["session_status"] == 4
assert await _session_status(db_engine, session_id) == 1 # 목록은 파생 표시만, 쓰기는 하지 않는다
async def test_list_marks_stale_round_not_renegotiable(client, db_engine, nego_seed):
"""검증: 개찰(결렬) 마감된 1차 견적에 2차가 이미 생성돼 있는 체인.
기대결과: renegotiable False — 다음 라운드가 있으면 재협상 요청 대상이 아니다(체인 최대 차수 판정)."""
async with db_engine.begin() as conn:
await _seed_case(conn, "CHAIN", 3, 2, -2, 3, nego_seed["supplier_id"])
await conn.execute(text(
f"UPDATE quotation.quotations SET close_reason = 5 WHERE number = '{MARK}CHAIN'"))
# 같은 견적번호의 2차 — 번호가 같아야 체인으로 묶인다.
await conn.execute(text(
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, round, start_time, end_time) "
f"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '견적 CHAIN 2차', '{MARK}CHAIN', 2, 2, 2, now(), now() + make_interval(hours => 2))"))
token = await _login_token(client)
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CHAIN")
assert listed["result"] == 3 and listed["renegotiable"] is False
async def test_list_has_chat_flags_sessions_with_history(client, db_engine, nego_seed):
"""검증: 대화 이력이 있는 세션과 없는 세션의 has_chat.
기대결과: 이력 있는 건만 True — 종료 건의 '결과 보기' 노출이 이 값으로 갈린다."""
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO negotiation.chats (session_id, seq, sender, target_price) VALUES (:sid, 1, 1, 0)"),
{"sid": nego_seed["sids"]["C"]},
)
token = await _login_token(client)
by_code = {i["item_code"]: i["has_chat"] for i in (await _list(client, token)).json()["items"]}
assert by_code[f"{MARK}C"] is True
assert by_code[f"{MARK}A"] is False
async def test_list_filter_qt_type(client, nego_seed):
token = await _login_token(client)
body = (await _list(client, token, qt_type=2)).json()
@@ -316,6 +385,40 @@ async def test_reject_success(client, nego_seed, db_engine):
assert status == 5 and reason == "단종 상품입니다" # REJECTED + 사유 저장
async def test_reject_with_price_and_opinion(client, nego_seed, db_engine):
# 채팅 내 협상 거부 경로 — 사유 외에 공급 희망 가격과 의견까지 함께 남긴다.
token = await _login_token(client)
sid = nego_seed["sids"]["B"]
r = await client.post(
f"/v1/negotiation/sessions/{sid}/reject",
headers={"Authorization": f"Bearer {token}"},
json={"reject_reason": "품절", "reject_price": 88000, "opinion": "대체품으로 재견적 부탁드립니다"},
)
assert r.json()["result"]["success"] is True
async with db_engine.begin() as conn:
row = (await conn.execute(
text("SELECT status, reject_reason, reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
{"sid": sid},
)).first()
assert row.status == 5 and row.reject_reason == "품절"
assert row.reject_price == 88000
assert row.custom["opinion"] == "대체품으로 재견적 부탁드립니다"
async def test_reject_without_price_keeps_null(client, nego_seed, db_engine):
# 목록 거부 경로 — 가격이 없으면 reject_price 를 건드리지 않는다.
token = await _login_token(client)
sid = nego_seed["sids"]["B"]
r = await _reject(client, token, sid, "단종")
assert r.json()["result"]["success"] is True
async with db_engine.begin() as conn:
row = (await conn.execute(
text("SELECT reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
{"sid": sid},
)).first()
assert row.reject_price is None and row.custom is None
async def test_reject_empty_reason(client, nego_seed):
token = await _login_token(client)
r = await _reject(client, token, nego_seed["sids"]["B"], " ") # 공백만 → 사유 없음
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.
@@ -0,0 +1,157 @@
import AppKit
import CoreGraphics
import Foundation
let output = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "docs/AIO2O-요청사항-반영보고서.pdf"
let W: CGFloat = 595, H: CGFloat = 842, M: CGFloat = 42
let navy = NSColor(calibratedRed: 0.06, green: 0.08, blue: 0.16, alpha: 1)
let ink = NSColor(calibratedRed: 0.11, green: 0.13, blue: 0.18, alpha: 1)
let muted = NSColor(calibratedRed: 0.39, green: 0.43, blue: 0.50, alpha: 1)
let paper = NSColor(calibratedRed: 0.98, green: 0.985, blue: 0.995, alpha: 1)
let line = NSColor(calibratedRed: 0.86, green: 0.88, blue: 0.92, alpha: 1)
let purple = NSColor(calibratedRed: 0.48, green: 0.25, blue: 0.92, alpha: 1)
let green = NSColor(calibratedRed: 0.08, green: 0.60, blue: 0.37, alpha: 1)
let orange = NSColor(calibratedRed: 0.94, green: 0.48, blue: 0.10, alpha: 1)
let red = NSColor(calibratedRed: 0.85, green: 0.24, blue: 0.28, alpha: 1)
let blue = NSColor(calibratedRed: 0.13, green: 0.39, blue: 0.92, alpha: 1)
func pr(_ r: CGRect) -> CGRect { CGRect(x: r.minX, y: H-r.maxY, width: r.width, height: r.height) }
func font(_ s: CGFloat, _ w: NSFont.Weight = .regular) -> NSFont {
NSFont(name: "Apple SD Gothic Neo", size: s) ?? .systemFont(ofSize: s, weight: w)
}
func style(_ s: CGFloat, _ c: NSColor = ink, _ w: NSFont.Weight = .regular,
_ a: NSTextAlignment = .left, _ spacing: CGFloat = 2.5) -> [NSAttributedString.Key:Any] {
let p = NSMutableParagraphStyle(); p.alignment = a; p.lineSpacing = spacing; p.lineBreakMode = .byWordWrapping
return [.font:font(s,w), .foregroundColor:c, .paragraphStyle:p]
}
func text(_ t:String,_ r:CGRect,_ s:CGFloat=10,_ c:NSColor=ink,_ w:NSFont.Weight = .regular,
_ a:NSTextAlignment = .left,_ spacing:CGFloat=2.5) {
NSAttributedString(string:t,attributes:style(s,c,w,a,spacing)).draw(with:pr(r),options:[.usesLineFragmentOrigin,.usesFontLeading])
}
func box(_ r:CGRect,_ fill:NSColor = .white,_ stroke:NSColor? = line,_ radius:CGFloat=10) {
let p=NSBezierPath(roundedRect:pr(r),xRadius:radius,yRadius:radius); fill.setFill(); p.fill()
if let stroke { stroke.setStroke(); p.lineWidth=0.8; p.stroke() }
}
func pill(_ t:String,_ r:CGRect,_ c:NSColor) {
box(r,c.withAlphaComponent(0.12),nil,r.height/2)
text(t,CGRect(x:r.minX,y:r.minY+4,width:r.width,height:r.height-7),8.2,c,.semibold,.center,1)
}
func begin(_ ctx:CGContext,_ page:Int,_ title:String) {
ctx.beginPDFPage(nil); ctx.saveGState(); NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current=NSGraphicsContext(cgContext:ctx,flipped:false)
paper.setFill(); NSBezierPath(rect:pr(CGRect(x:0,y:0,width:W,height:H))).fill()
text(title,CGRect(x:M,y:30,width:420,height:16),7.5,muted,.medium)
text(String(format:"%02d",page),CGRect(x:W-M-30,y:30,width:30,height:16),8,muted,.medium,.right)
let p=NSBezierPath(); p.move(to:CGPoint(x:M,y:31)); p.line(to:CGPoint(x:W-M,y:31))
line.setStroke(); p.lineWidth=0.7; p.stroke()
}
func end(_ ctx:CGContext) {
NSGraphicsContext.restoreGraphicsState(); ctx.restoreGState(); ctx.endPDFPage()
}
func heading(_ n:String,_ t:String,_ sub:String) {
pill(n,CGRect(x:M,y:54,width:34,height:24),purple)
text(t,CGRect(x:86,y:49,width:465,height:30),21,navy,.bold)
text(sub,CGRect(x:M,y:87,width:W-2*M,height:31),9.5,muted,.regular,.left,3)
}
func statusRow(_ no:String,_ title:String,_ body:String,_ status:String,_ c:NSColor,_ y:CGFloat,_ h:CGFloat=82) {
box(CGRect(x:M,y:y,width:W-2*M,height:h),.white,line,9)
pill(no,CGRect(x:M+12,y:y+13,width:28,height:20),c)
text(title,CGRect(x:M+50,y:y+12,width:338,height:19),10.5,navy,.bold)
pill(status,CGRect(x:W-M-102,y:y+12,width:90,height:21),c)
text(body,CGRect(x:M+50,y:y+37,width:W-2*M-64,height:h-44),8.8,ink,.regular,.left,2.4)
}
func metric(_ value:String,_ label:String,_ x:CGFloat,_ c:NSColor) {
box(CGRect(x:x,y:435,width:117,height:96),c.withAlphaComponent(0.08),c.withAlphaComponent(0.3),12)
text(value,CGRect(x:x+8,y:454,width:101,height:32),25,c,.bold,.center)
text(label,CGRect(x:x+8,y:493,width:101,height:20),9,muted,.medium,.center)
}
var media=CGRect(x:0,y:0,width:W,height:H)
guard let consumer=CGDataConsumer(url:URL(fileURLWithPath:output) as CFURL),
let ctx=CGContext(consumer:consumer,mediaBox:&media,nil) else { fatalError("PDF 생성 실패") }
// 1. cover
begin(ctx,1,"AIO2O · 요청사항 반영 보고서")
box(CGRect(x:0,y:0,width:W,height:H),navy,nil,0)
pill("IMPLEMENTATION REVIEW",CGRect(x:M,y:112,width:148,height:25),NSColor(calibratedRed:0.42,green:0.78,blue:1,alpha:1))
text("AIO2O 테스트 및 요청사항\n반영 결과 보고서",CGRect(x:M,y:166,width:510,height:112),34,.white,.bold,.left,7)
text("260727_AIO2O 테스트 및 요청사항.xlsx 기준\n현재 저장소 구현·커밋·검증 캡처 대조",CGRect(x:M,y:310,width:510,height:60),14,NSColor(calibratedWhite:0.78,alpha:1),.regular,.left,7)
box(CGRect(x:M,y:435,width:W-2*M,height:176),NSColor.white.withAlphaComponent(0.07),NSColor.white.withAlphaComponent(0.12),16)
text("결론",CGRect(x:M+22,y:458,width:460,height:25),13,.white,.bold)
text("핵심 업무 흐름은 대부분 구현되었습니다. 견적 목록·상세, 재협상 접수, 목표가 자동계산, 인터넷 최저가, 종료 의견, 결렬폼 통일, VAT 별도 표기, 10원 반올림은 코드 근거가 확인됩니다.\n\n다만 절충안/자동 제안가의 업무 적정성, SG명·유통레벨의 최종 UX, 최저가 VAT 산식은 추가 확인이 필요합니다.",CGRect(x:M+22,y:495,width:W-2*M-44,height:96),11,NSColor(calibratedWhite:0.88,alpha:1),.regular,.left,5)
text("작성일 2026.07.31 | 기준 브랜치 feature/negodata | HEAD 775984fe",CGRect(x:M,y:758,width:W-2*M,height:18),8.5,NSColor(calibratedWhite:0.60,alpha:1))
end(ctx)
// 2. summary
begin(ctx,2,"AIO2O · 요청사항 반영 보고서")
heading("01","종합 요약","엑셀 RAW 시트의 24개 요청을 현재 저장소 상태로 재판정했습니다. 중복 요청은 원 요청 번호를 유지했습니다.")
metric("18","완료·반영",M,green); metric("3","부분 반영",M+130,orange); metric("3","확인 필요",M+260,red); metric("24","전체 항목",M+390,blue)
text("판정 기준",CGRect(x:M,y:566,width:507,height:24),13,navy,.bold)
statusRow("A","완료·반영","사용자 화면과 처리 로직이 모두 확인되거나, 동일 기능을 제공하는 구현 및 검증 캡처가 존재합니다.","18건",green,603,60)
statusRow("B","부분 반영","핵심 기능은 있으나 요청한 명칭·선택값·산식 중 일부가 다르거나 배포/운영 확인이 남았습니다.","3건",orange,675,60)
statusRow("C","확인 필요","코드는 존재하지만 계산 결과의 업무 적정성을 확정할 수 없거나 요청 산식이 명시적으로 확인되지 않습니다.","3건",red,747,60)
end(ctx)
// 3. system 1
begin(ctx,3,"AIO2O · 요청사항 반영 보고서")
heading("02","기본 시스템 반영 내역","견적 생성부터 협력사·최저가·협상 화면까지의 공통 요청입니다.")
statusRow("01","견적관리 목록·상세/히스토리","견적 목록과 상세 드로어가 있으며, 상세의 채팅 탭·협상카드 탭이 세션 데이터를 연결합니다. 견적번호별 진행/완료 상태와 상세 확인 경로가 마련됐습니다.","완료",green,132)
statusRow("02","재협상 접수 및 관리","공급사 포털에서 결렬 건 재협상 요청·철회가 가능하고, 구매자 화면에 재협상 요청 목록·검토 시트·승인/반려 및 알림이 구현됐습니다.","완료",green,226)
statusRow("03","MD 제시가 용어·위치·판매가","‘MD’는 ‘구매담당자’로 통일했고 제시가/산정후보를 ‘3. 낙찰기준’으로 이동했습니다. 판매가 설정은 숨김 처리되어 요청 흐름과 일치합니다.","완료",green,320)
statusRow("04","목표가 자동 산출","매입가 × (1 − 목표 네고율)로 구매담당자 제시가를 자동 입력합니다. 예: 10,000원, 2% → 9,800원. 프론트 자동계산과 백엔드 가격 처리 근거가 있습니다.","완료",green,414)
statusRow("05","공급사/매입가 라벨 일원화","상품 및 견적 화면의 회사별 필드 라벨 설정을 연동해 ‘공급사=매입가’ 표기 정책을 적용할 수 있게 했습니다. 실제 운영 회사 설정값 확인은 필요합니다.","부분",orange,508)
statusRow("06","인터넷 최저가 수집","15%에서 멈추던 Worker/큐 처리 문제를 수정하고, 몰별 결과·진행 상태·이력 화면을 재설계했습니다. 다만 요청 산식 ‘(상품가+배송비)/1.1’의 최종 대표값 적용은 코드에서 확정되지 않습니다.","부분",orange,602)
statusRow("07","신규 상품 공급사 입력","신규 상품 등록 폼에 공급사 선택기를 추가하고 상품–공급사 매핑을 저장하도록 구현했습니다.","완료",green,696)
end(ctx)
// 4. system 2
begin(ctx,4,"AIO2O · 요청사항 반영 보고서")
heading("03","협력사·협상 화면 반영","용어 통일, 종료 단계, 가격 표기와 협상 지표를 중심으로 확인했습니다.")
statusRow("08","협력사 SG명·유통레벨","취급상품 기반 분류와 공급유형 선택/저장은 구현되어 있습니다. 다만 요청한 SG명 콤보와 유통레벨 4종(제조·총판·대리점·일반유통), 취급상품 삭제가 그대로 완성됐는지는 추가 UX 확인이 필요합니다.","부분",orange,132)
statusRow("09","리드타임 → 표준납기","협상 완료 부가정보와 API 설명에 ‘표준납기’가 반영되고 회사 정의 session_fields와 연결됩니다.","완료",green,226)
statusRow("10","협상 단가 VAT 별도","협상 상품정보·요약·목록/상세의 단가 표기를 VAT 별도로 통일했습니다. 검증 캡처도 존재합니다.","완료",green,320)
statusRow("11","협상 성공률 기준 안내","성공률은 공급사 제시가를 앵커가·목표가와 비교한 1~99 지표입니다. 100% 미달이 결렬 조건은 아니며, 실제 종료는 별도 낙찰/개찰 규칙이 결정합니다.","완료(안내)",blue,414)
statusRow("12","협상 종료 추가 의견","타결 부가정보와 결렬 통합폼 모두 ‘기타 의견’을 받으며 sessions.custom.opinion에 저장합니다. 구매자 상세·요약에서 조회되고 완료 후 잠깁니다.","완료",green,508)
statusRow("13","결렬 사유·희망가격 통일","기존 RejectRSP/RejectCM을 단일 RejectForm으로 교체했습니다. 결렬사유·희망가·의견을 한 흐름에서 받고 reject_reason/reject_price에 저장합니다.","완료",green,602)
statusRow("14","카드 사용 횟수 제한","견적 설정의 card_count(기본 3)를 컨텍스트에서 읽어 실제 사용 가능한 카드 수와 종료 조건을 제한하도록 반영했습니다. 운영 시 기존 세션 회귀검증을 권장합니다.","완료",green,696)
end(ctx)
// 5. case-specific
begin(ctx,5,"AIO2O · 요청사항 반영 보고서")
heading("04","견적번호별 이슈 반영","EST-202607-05DE·8945·C9D2 사례에서 제기된 가격/종료 흐름을 대조했습니다.")
statusRow("15","앵커·자동 제안가 10원 반올림","앵커 생성가, 목표가 후보, 협상카드 카운터를 공통으로 10원 단위 반올림합니다. 예: 15,213원 → 15,210원. 관련 커밋과 단위 테스트가 있습니다.","완료",green,132)
statusRow("16","절충안 계산식","협상카드 전술에는 앵커·목표가·직전 제시가를 이용한 중간값 및 목표가 상한 로직이 존재합니다. 다만 ‘절충안’의 기대 공식이 엑셀에 없어 업무적으로 맞는지 확정할 수 없습니다.","확인 필요",red,226)
statusRow("17","05DE/C9D2 결렬 희망가격","견적 유형별로 갈리던 결렬 화면을 단일 폼으로 통합해 희망가격 입력 절차를 동일하게 만들었습니다.","완료",green,320)
statusRow("18","8945 협상 마무리 개편","종료 후 표준납기·MOQ·발주배수·배송유형 등 회사 정의 부가정보를 선택/입력하고, 기타 의견과 함께 최종 요약에 반영합니다. 배송 선택값은 회사 설정에 따라 구성됩니다.","완료",green,414)
statusRow("19","C9D2 자동 제안가 갭","제안가는 카드 전술과 앵커·목표가·직전 제시가의 조합으로 계산되고 10원 반올림됩니다. 17,500원→15,210원의 10.5% 갭이 정책상 적정한지는 목표/앵커 설정을 포함한 별도 검증이 필요합니다.","확인 필요",red,508)
statusRow("20","성공/실패 후 의견 조회","협력사가 입력한 종료 의견은 공급사 요약과 구매자 견적 상세 양쪽에서 확인할 수 있고, 종료 후 읽기 전용으로 잠깁니다.","완료",green,602)
statusRow("21","중복 요청 통합 반영","엑셀 18/22(성공률), 19/25(종료 의견), 5/23(목표가), 14/17/20(결렬폼)은 각각 하나의 공통 구현으로 해소했습니다.","완료",green,696)
end(ctx)
// 6. evidence
begin(ctx,6,"AIO2O · 요청사항 반영 보고서")
heading("05","구현 근거","최근 커밋과 현재 코드에서 확인한 핵심 근거입니다. 커밋 단위로 기능 범위를 추적할 수 있습니다.")
statusRow("A","b33ae05c · 견적 가격/상품/라벨","목표가 자동입력, 산정후보 위치 이동, 앵커·후보 10원 반올림, 신규 상품 공급사 입력, 회사 설정 라벨 연동.","커밋",purple,132,72)
statusRow("B","a56589c6 · 종료폼/의견/VAT","결렬폼 통합, 희망가·사유 저장, 타결/결렬 의견 수취, 상품정보 라벨 연동, 협상 단가 VAT 별도 표기.","커밋",purple,216,72)
statusRow("C","30f13483 · 인터넷 최저가","무한 로딩 버그 수정, Worker 설정 보강, 몰별 최저가·진행/상세 UI 및 이력 저장 개선.","커밋",purple,300,72)
statusRow("D","9dca78dc · 완료 부가정보","완료 부가정보 수취·요약 표시·잠금, 구매자 상세 노출, VAT 표기 통일.","커밋",purple,384,72)
statusRow("E","2a004734 · 견적 상세 연결","견적 상세의 채팅·협상카드 탭 연동과 드로어 탐색 개선.","커밋",purple,468,72)
statusRow("F","775984fe / f554202c · 반올림","협상카드 카운터와 자동 앵커를 10원 단위 반올림으로 통일.","커밋",purple,552,72)
statusRow("G","화면 검증 캡처","목록/상세, 종료 의견, VAT, 완료 요약, 읽기 전용 잠금 등 12개 캡처가 저장소 루트에 남아 있습니다.","캡처",blue,636,72)
text("주의: 본 보고서는 2026-07-31 현재 로컬 저장소의 코드·커밋·캡처를 기준으로 합니다. 운영 배포 여부와 기존 데이터 마이그레이션 상태는 별도 확인 대상입니다.",CGRect(x:M,y:742,width:W-2*M,height:42),8.8,muted,.regular,.left,3)
end(ctx)
// 7. actions
begin(ctx,7,"AIO2O · 요청사항 반영 보고서")
heading("06","남은 확인 및 권고","기능 누락이라기보다 업무 규칙·운영 설정을 확정해야 하는 항목입니다.")
statusRow("1","최저가 VAT 대표값 확정","현재 LPS는 상품가와 배송비를 별도 수집·표시합니다. 대표 최저가를 반드시 (상품가+배송비)/1.1로 저장할지, 화면 표시만 할지 정책을 확정한 뒤 테스트를 추가해야 합니다.","우선순위 높음",red,142,98)
statusRow("2","절충안/자동 제안가 기준 검증","05DE·C9D2의 실제 앵커가·목표가·직전 제시가를 넣어 계산 결과를 재현하고, 허용 최대 인하폭 또는 목표가 클램프 기준을 업무 담당자와 합의하는 것이 좋습니다.","우선순위 높음",red,254,98)
statusRow("3","SG명·유통레벨 UX 확정","현행 취급상품 기반 분류/공급유형을 요청한 SG 콤보와 유통레벨 4종으로 대체할지, 데이터 모델을 유지한 채 라벨만 조정할지 결정이 필요합니다.","우선순위 중간",orange,366,98)
statusRow("4","운영 배포·기존 세션 회귀검증","종료폼, 의견, 카드 횟수 제한은 신규 코드에 반영됐습니다. 운영 컨테이너 재빌드 후 기존 세션과 신규 세션에서 각각 1회 이상 확인해야 합니다.","배포 확인",blue,478,98)
box(CGRect(x:M,y:612,width:W-2*M,height:118),purple.withAlphaComponent(0.08),purple.withAlphaComponent(0.28),12)
text("권장 최종 승인 기준",CGRect(x:M+18,y:630,width:470,height:22),12,purple,.bold)
text("① 운영 배포 버전 확인 ② 대표 견적 3건 시나리오 재실행 ③ 계산식 2건 서면 확정\n④ SG/유통레벨 화면 승인 ⑤ 완료·결렬 의견이 구매자 상세에 저장되는지 확인",CGRect(x:M+18,y:662,width:470,height:50),10,ink,.medium,.left,5)
text("— End of report —",CGRect(x:M,y:760,width:W-2*M,height:20),8,muted,.medium,.center)
end(ctx)
ctx.closePDF()
Binary file not shown.
+790
View File
@@ -0,0 +1,790 @@
import AppKit
import CoreGraphics
import Foundation
let outPath = CommandLine.arguments.count > 1
? CommandLine.arguments[1]
: "docs/backend-advanced-concepts-ko.pdf"
let W: CGFloat = 595
let H: CGFloat = 842
let margin: CGFloat = 44
let navy = NSColor(calibratedRed: 0.055, green: 0.086, blue: 0.16, alpha: 1)
let ink = NSColor(calibratedRed: 0.10, green: 0.13, blue: 0.18, alpha: 1)
let muted = NSColor(calibratedRed: 0.37, green: 0.42, blue: 0.50, alpha: 1)
let paper = NSColor(calibratedRed: 0.975, green: 0.98, blue: 0.99, alpha: 1)
let line = NSColor(calibratedRed: 0.86, green: 0.88, blue: 0.92, alpha: 1)
let blue = NSColor(calibratedRed: 0.16, green: 0.39, blue: 0.93, alpha: 1)
let cyan = NSColor(calibratedRed: 0.10, green: 0.69, blue: 0.74, alpha: 1)
let green = NSColor(calibratedRed: 0.10, green: 0.63, blue: 0.39, alpha: 1)
let orange = NSColor(calibratedRed: 0.94, green: 0.47, blue: 0.12, alpha: 1)
let red = NSColor(calibratedRed: 0.88, green: 0.25, blue: 0.28, alpha: 1)
let purple = NSColor(calibratedRed: 0.48, green: 0.32, blue: 0.89, alpha: 1)
func pdfRect(_ r: CGRect) -> CGRect {
CGRect(x: r.minX, y: H - r.maxY, width: r.width, height: r.height)
}
func pdfPoint(_ p: CGPoint) -> CGPoint {
CGPoint(x: p.x, y: H - p.y)
}
func font(_ size: CGFloat, _ weight: NSFont.Weight = .regular) -> NSFont {
NSFont(name: "Apple SD Gothic Neo", size: size)
?? NSFont.systemFont(ofSize: size, weight: weight)
}
func mono(_ size: CGFloat) -> NSFont {
NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
}
func attrs(_ size: CGFloat, color: NSColor = ink, weight: NSFont.Weight = .regular,
align: NSTextAlignment = .left, lineSpacing: CGFloat = 3) -> [NSAttributedString.Key: Any] {
let p = NSMutableParagraphStyle()
p.alignment = align
p.lineSpacing = lineSpacing
p.lineBreakMode = .byWordWrapping
return [.font: font(size, weight), .foregroundColor: color, .paragraphStyle: p]
}
func drawText(_ text: String, _ rect: CGRect, size: CGFloat = 11, color: NSColor = ink,
weight: NSFont.Weight = .regular, align: NSTextAlignment = .left,
lineSpacing: CGFloat = 3) {
NSAttributedString(string: text, attributes: attrs(size, color: color, weight: weight,
align: align, lineSpacing: lineSpacing))
.draw(with: pdfRect(rect), options: [.usesLineFragmentOrigin, .usesFontLeading])
}
func rounded(_ rect: CGRect, radius: CGFloat = 12, fill: NSColor = .white,
stroke: NSColor? = line, width: CGFloat = 1) {
let p = NSBezierPath(roundedRect: pdfRect(rect), xRadius: radius, yRadius: radius)
fill.setFill(); p.fill()
if let stroke { stroke.setStroke(); p.lineWidth = width; p.stroke() }
}
func pill(_ text: String, x: CGFloat, y: CGFloat, w: CGFloat, color: NSColor) {
rounded(CGRect(x: x, y: y, width: w, height: 25), radius: 12.5,
fill: color.withAlphaComponent(0.12), stroke: nil)
drawText(text, CGRect(x: x, y: y + 5, width: w, height: 16), size: 9.5,
color: color, weight: .semibold, align: .center)
}
func arrow(_ from: CGPoint, _ to: CGPoint, color: NSColor = muted) {
let from = pdfPoint(from), to = pdfPoint(to)
let p = NSBezierPath(); p.move(to: from); p.line(to: to)
color.setStroke(); p.lineWidth = 1.8; p.stroke()
let a = atan2(to.y - from.y, to.x - from.x)
let l: CGFloat = 7
let h = NSBezierPath()
h.move(to: to)
h.line(to: CGPoint(x: to.x - l * cos(a - .pi / 6), y: to.y - l * sin(a - .pi / 6)))
h.line(to: CGPoint(x: to.x - l * cos(a + .pi / 6), y: to.y - l * sin(a + .pi / 6)))
h.close(); color.setFill(); h.fill()
}
func node(_ title: String, _ sub: String, rect: CGRect, color: NSColor) {
rounded(rect, radius: 10, fill: color.withAlphaComponent(0.10),
stroke: color.withAlphaComponent(0.55), width: 1.2)
drawText(title, CGRect(x: rect.minX + 8, y: rect.minY + 10, width: rect.width - 16, height: 18),
size: 10.5, color: color, weight: .bold, align: .center)
drawText(sub, CGRect(x: rect.minX + 8, y: rect.minY + 31, width: rect.width - 16, height: rect.height - 36),
size: 8.5, color: muted, align: .center, lineSpacing: 1)
}
func sectionTitle(_ number: String, _ title: String, _ subtitle: String, color: NSColor) {
pill(number, x: margin, y: 48, w: 34, color: color)
drawText(title, CGRect(x: 86, y: 46, width: 450, height: 30), size: 22,
color: navy, weight: .bold)
drawText(subtitle, CGRect(x: margin, y: 82, width: W - 2 * margin, height: 26),
size: 10.5, color: muted)
}
func footer(_ page: Int, _ label: String = "O2O Negosium · Backend Concepts") {
let p = NSBezierPath()
p.move(to: CGPoint(x: margin, y: H - 34)); p.line(to: CGPoint(x: W - margin, y: H - 34))
line.setStroke(); p.lineWidth = 0.7; p.stroke()
drawText(label, CGRect(x: margin, y: H - 28, width: 350, height: 14), size: 7.5, color: muted)
drawText("\(page)", CGRect(x: W - margin - 35, y: H - 28, width: 35, height: 14),
size: 8, color: muted, align: .right)
}
func callout(_ title: String, _ body: String, rect: CGRect, color: NSColor) {
rounded(rect, radius: 12, fill: color.withAlphaComponent(0.08),
stroke: color.withAlphaComponent(0.35))
rounded(CGRect(x: rect.minX, y: rect.minY, width: 5, height: rect.height),
radius: 2.5, fill: color, stroke: nil)
drawText(title, CGRect(x: rect.minX + 16, y: rect.minY + 12,
width: rect.width - 28, height: 20),
size: 11, color: color, weight: .bold)
drawText(body, CGRect(x: rect.minX + 16, y: rect.minY + 37,
width: rect.width - 28, height: rect.height - 45),
size: 9.5, color: ink, lineSpacing: 3)
}
func comparison(_ leftTitle: String, _ left: String, _ rightTitle: String, _ right: String,
y: CGFloat, color: NSColor) {
let gap: CGFloat = 14
let cw = (W - 2 * margin - gap) / 2
callout(leftTitle, left, rect: CGRect(x: margin, y: y, width: cw, height: 126), color: red)
callout(rightTitle, right, rect: CGRect(x: margin + cw + gap, y: y, width: cw, height: 126), color: color)
}
func codeBox(_ title: String, _ path: String, _ code: String, rect: CGRect, accent: NSColor) {
rounded(rect, radius: 10, fill: navy, stroke: nil)
drawText(title, CGRect(x: rect.minX + 14, y: rect.minY + 11,
width: rect.width - 28, height: 17),
size: 10, color: .white, weight: .bold)
drawText(path, CGRect(x: rect.minX + 14, y: rect.minY + 30,
width: rect.width - 28, height: 14),
size: 7.5, color: accent)
let p = NSMutableParagraphStyle(); p.lineSpacing = 2; p.lineBreakMode = .byClipping
NSAttributedString(string: code, attributes: [.font: mono(7.8), .foregroundColor: NSColor(calibratedWhite: 0.88, alpha: 1), .paragraphStyle: p])
.draw(with: pdfRect(CGRect(x: rect.minX + 14, y: rect.minY + 51,
width: rect.width - 28, height: rect.height - 60)),
options: [.usesLineFragmentOrigin])
}
func beginPage(_ ctx: CGContext, page: Int, label: String = "O2O Negosium · Backend Concepts") {
ctx.beginPDFPage(nil)
ctx.saveGState()
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(cgContext: ctx, flipped: false)
paper.setFill(); NSBezierPath(rect: pdfRect(CGRect(x: 0, y: 0, width: W, height: H))).fill()
footer(page, label)
}
func endPage(_ ctx: CGContext) {
NSGraphicsContext.restoreGraphicsState()
ctx.restoreGState()
ctx.endPDFPage()
}
var mediaBox = CGRect(x: 0, y: 0, width: W, height: H)
guard let consumer = CGDataConsumer(url: URL(fileURLWithPath: outPath) as CFURL),
let ctx = CGContext(consumer: consumer, mediaBox: &mediaBox, nil) else {
fatalError("PDF context 생성 실패")
}
// 1 — Cover
beginPage(ctx, page: 1, label: "O2O Negosium · Backend Field Guide")
rounded(CGRect(x: 0, y: 0, width: W, height: H), radius: 0, fill: navy, stroke: nil)
for i in 0..<7 {
let x = CGFloat(50 + i * 78)
let c = [blue, cyan, green, orange, purple][i % 5]
rounded(CGRect(x: x, y: 85 + CGFloat((i % 3) * 28), width: 48, height: 48),
radius: 24, fill: c.withAlphaComponent(0.35), stroke: nil)
}
drawText("BACKEND", CGRect(x: margin, y: 190, width: 507, height: 35), size: 15,
color: cyan, weight: .bold)
drawText("어려운 개념 5가지,\n코드로 이해하기", CGRect(x: margin, y: 228, width: 507, height: 118),
size: 36, color: .white, weight: .bold, lineSpacing: 7)
drawText("분산 시스템 · 트랜잭션/동시성 · 멀티테넌시\n캐시 정합성 · 스케줄러/배치",
CGRect(x: margin, y: 370, width: 507, height: 62), size: 15,
color: NSColor(calibratedWhite: 0.80, alpha: 1), lineSpacing: 8)
rounded(CGRect(x: margin, y: 485, width: 507, height: 154), radius: 18,
fill: NSColor.white.withAlphaComponent(0.07),
stroke: NSColor.white.withAlphaComponent(0.15))
drawText("이 문서는 이렇게 읽어요", CGRect(x: 66, y: 510, width: 455, height: 25),
size: 14, color: .white, weight: .bold)
drawText("① 일상 비유로 개념 잡기\n② 실제 서비스 흐름을 그림으로 보기\n③ 프로젝트 코드에서 구현 확인하기\n④ 없을 때 생기는 문제와 비교하기",
CGRect(x: 66, y: 548, width: 455, height: 78), size: 11.5,
color: NSColor(calibratedWhite: 0.88, alpha: 1), lineSpacing: 6)
drawText("Generated from the current repository · 2026-07-29",
CGRect(x: margin, y: 758, width: 507, height: 18), size: 8.5,
color: NSColor(calibratedWhite: 0.62, alpha: 1))
endPage(ctx)
// 2 — Architecture map
beginPage(ctx, page: 2)
drawText("먼저, 서비스 지도를 봅시다", CGRect(x: margin, y: 48, width: 507, height: 34),
size: 24, color: navy, weight: .bold)
drawText("다섯 개념은 따로 노는 것이 아니라, 한 요청이 여러 서비스와 저장소를 지나면서 함께 작동합니다.",
CGRect(x: margin, y: 88, width: 507, height: 32), size: 10.5, color: muted)
node("사용자", "브라우저", rect: CGRect(x: 44, y: 170, width: 90, height: 62), color: purple)
node("Backend", "채팅·공급사", rect: CGRect(x: 184, y: 145, width: 102, height: 72), color: blue)
node("Agent", "AI 협상", rect: CGRect(x: 348, y: 145, width: 102, height: 72), color: orange)
node("Negodata", "견적·관리", rect: CGRect(x: 184, y: 270, width: 102, height: 72), color: cyan)
node("LPS", "최저가 Worker", rect: CGRect(x: 348, y: 270, width: 102, height: 72), color: green)
node("PostgreSQL", "업무 원본", rect: CGRect(x: 184, y: 405, width: 130, height: 72), color: purple)
node("Redis", "앵커링 캐시", rect: CGRect(x: 368, y: 405, width: 100, height: 72), color: red)
arrow(CGPoint(x: 134, y: 200), CGPoint(x: 184, y: 182), color: purple)
arrow(CGPoint(x: 286, y: 180), CGPoint(x: 348, y: 180), color: blue)
arrow(CGPoint(x: 235, y: 217), CGPoint(x: 235, y: 270), color: cyan)
arrow(CGPoint(x: 286, y: 304), CGPoint(x: 348, y: 304), color: green)
arrow(CGPoint(x: 235, y: 342), CGPoint(x: 235, y: 405), color: purple)
arrow(CGPoint(x: 399, y: 342), CGPoint(x: 415, y: 405), color: red)
callout("① 경계가 생기면 ‘분산 시스템’", "서비스 A가 서비스 B를 네트워크로 호출하는 순간, 지연·타임아웃·부분 실패를 다뤄야 합니다.",
rect: CGRect(x: margin, y: 525, width: 246, height: 105), color: blue)
callout("② 여러 실행자가 만나면 ‘동시성’", "사용자 클릭과 스케줄러가 같은 견적을 동시에 마감할 수 있어, DB가 최종 심판 역할을 합니다.",
rect: CGRect(x: 305, y: 525, width: 246, height: 105), color: orange)
callout("③ 빠르게 읽되 원본을 지키면 ‘캐시’", "Redis와 프로세스 메모리는 복사본입니다. PostgreSQL과 설정 파일이 원본입니다.",
rect: CGRect(x: margin, y: 650, width: 246, height: 105), color: red)
callout("④ 회사별 경계를 지키면 ‘멀티테넌시’", "요청 헤더에서 회사 ID를 결정하고, 회사별 설정·엔진을 선택합니다.",
rect: CGRect(x: 305, y: 650, width: 246, height: 105), color: purple)
endPage(ctx)
// 3 — Distributed systems: concept first
beginPage(ctx, page: 3)
sectionTitle("3", "분산 시스템 — 개념부터", "여러 독립 실행 단위가 네트워크를 통해 하나의 업무를 완성하는 시스템", color: blue)
callout("정확한 정의", "프로세스·컨테이너·서버가 각자 메모리와 실행 상태를 가지고, HTTP나 메시지로 통신하는 구조입니다. 한 서비스의 함수 호출과 달리 상대의 상태를 직접 볼 수 없고, 네트워크 응답만으로 결과를 추론해야 합니다.",
rect: CGRect(x: margin, y: 126, width: 507, height: 92), color: blue)
drawText("왜 어려운가: 네트워크에는 네 가지 결과가 있습니다", CGRect(x: margin, y: 244, width: 507, height: 24),
size: 13.5, color: navy, weight: .bold)
let distCases: [(String, String, NSColor)] = [
("성공", "상대가 처리했고 응답도 받음", green),
("명확한 실패", "상대가 오류 응답을 보냄", red),
("연결 실패", "상대에게 요청이 도착하지 않음", orange),
("애매한 타임아웃", "처리는 됐지만 응답만 늦었을 수도 있음", purple),
]
for (i, c) in distCases.enumerated() {
let col = i % 2, row = i / 2
let x = margin + CGFloat(col) * 260
let y = CGFloat(286 + row * 86)
callout(c.0, c.1, rect: CGRect(x: x, y: y, width: 247, height: 70), color: c.2)
}
drawText("대표적인 대응 수단", CGRect(x: margin, y: 475, width: 507, height: 24),
size: 13.5, color: navy, weight: .bold)
callout("Timeout", "얼마나 기다릴지 상한을 둡니다. 짧으면 정상 요청도 실패하고, 길면 자원이 오래 묶입니다.",
rect: CGRect(x: margin, y: 515, width: 159, height: 92), color: blue)
callout("Retry", "일시 실패를 다시 시도합니다. 단, 중복 처리에 안전한 작업에서만 제한적으로 사용합니다.",
rect: CGRect(x: 218, y: 515, width: 159, height: 92), color: orange)
callout("Idempotency", "같은 요청을 여러 번 보내도 결과가 한 번 처리한 것과 같도록 만듭니다.",
rect: CGRect(x: 392, y: 515, width: 159, height: 92), color: purple)
callout("Fallback", "주 서비스가 실패하면 대체 경로·기본값·이전 데이터를 사용합니다. 대체 결과가 업무적으로 허용될 때만 가능합니다.",
rect: CGRect(x: margin, y: 630, width: 247, height: 92), color: green)
callout("Circuit breaker", "실패가 계속되는 서비스를 잠시 호출하지 않아 연쇄 장애를 막습니다. 현재 프로젝트에는 명시적 구현이 없습니다.",
rect: CGRect(x: 304, y: 630, width: 247, height: 92), color: red)
endPage(ctx)
// 4 distributed concept
beginPage(ctx, page: 4)
sectionTitle("3", "분산 시스템과 장애 대응", "한 프로그램이 아니라 여러 서비스가 네트워크로 협력하는 구조", color: blue)
callout("쉬운 비유", "한 식당 안에서 주방과 홀 직원이 말로 협업하는 것이 단일 시스템이라면, 분산 시스템은 서로 다른 건물의 팀이 전화로 협업하는 것입니다. 전화는 늦거나 끊길 수 있고, 상대가 일을 끝냈는데 답만 못 받을 수도 있습니다.",
rect: CGRect(x: margin, y: 130, width: 507, height: 105), color: blue)
drawText("프로젝트의 대표 흐름", CGRect(x: margin, y: 266, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
node("Backend", "사용자 채팅 요청", rect: CGRect(x: 52, y: 315, width: 110, height: 74), color: blue)
node("HTTPX", "timeout 설정", rect: CGRect(x: 242, y: 315, width: 110, height: 74), color: cyan)
node("Agent", "협상 턴 계산", rect: CGRect(x: 432, y: 315, width: 110, height: 74), color: orange)
arrow(CGPoint(x: 162, y: 352), CGPoint(x: 242, y: 352), color: blue)
arrow(CGPoint(x: 352, y: 352), CGPoint(x: 432, y: 352), color: cyan)
drawText("성공", CGRect(x: 394, y: 414, width: 80, height: 18), size: 9, color: green, weight: .bold)
arrow(CGPoint(x: 485, y: 389), CGPoint(x: 485, y: 458), color: green)
node("응답 반영", "채팅 상태 저장", rect: CGRect(x: 430, y: 458, width: 112, height: 65), color: green)
drawText("타임아웃/실패", CGRect(x: 185, y: 414, width: 105, height: 18), size: 9, color: red, weight: .bold)
arrow(CGPoint(x: 297, y: 389), CGPoint(x: 297, y: 458), color: red)
node("안전한 실패", "ok=false 반환", rect: CGRect(x: 241, y: 458, width: 112, height: 65), color: red)
callout("중요한 함정: 타임아웃 ≠ 상대가 아무 일도 안 함", "Agent가 DB 상태를 이미 전진시킨 직후 응답만 늦었을 수 있습니다. 그래서 무조건 재시도하면 같은 턴을 두 번 처리할 위험이 있습니다. 코드가 timed_out을 따로 표시하는 이유입니다.",
rect: CGRect(x: margin, y: 566, width: 507, height: 105), color: orange)
comparison("이 장치가 없으면", "Agent가 느린 순간 Backend 요청도 끝없이 대기합니다. 무작정 재시도하면 협상 step이 두 번 전진할 수 있습니다.",
"현재 방식", "HTTP timeout을 두고 성공/일반 실패/타임아웃을 구분합니다. 호출 경계에서 예외를 응답 객체로 변환합니다.",
y: 695, color: blue)
endPage(ctx)
// 5 distributed code
beginPage(ctx, page: 5)
sectionTitle("3", "분산 시스템 — 실제 코드", "서비스 경계마다 timeout, fallback, best-effort 정책이 다릅니다.", color: blue)
codeBox("Agent 호출: 타임아웃을 별도 상태로 반환",
"backend/services/agent_client.py · lines 81–91",
"""
async with httpx.AsyncClient(
base_url=agent_config.base_url,
timeout=agent_config.timeout_sec,
) as cli:
resp = await cli.post("/v1/chat", json=body, headers=headers)
except httpx.TimeoutException as ex:
# Agent가 이미 처리했을 수 있어 단순 재시도는 위험
return AgentTurn(ok=False, timed_out=True)
except Exception:
return AgentTurn(ok=False)
""",
rect: CGRect(x: margin, y: 130, width: 507, height: 245), accent: cyan)
codeBox("카탈로그 변경 알림: 핵심 업무를 막지 않는 best-effort",
"negodata/backend/services/agent_notify.py · lines 15–26",
"""
try:
async with httpx.AsyncClient(timeout=3.0) as cli:
await cli.post(f"{base}/v1/catalog-refresh-all")
except Exception as ex:
# 알림 실패는 카드 작업을 막지 않는다
LOG.w(f"[agent_notify] 변경 알림 실패(무시): {ex}")
""",
rect: CGRect(x: margin, y: 395, width: 507, height: 160), accent: green)
callout("어떻게 정책을 고르나요?", "결제처럼 반드시 성공해야 하는 작업은 실패를 호출자에게 알려 재처리해야 합니다. 반면 ‘캐시 무효화 알림’처럼 보조적인 작업은 실패해도 핵심 카드 변경을 성공시킬 수 있습니다. 모든 외부 호출을 똑같이 재시도하면 안 됩니다.",
rect: CGRect(x: margin, y: 580, width: 507, height: 105), color: blue)
drawText("기억할 단어", CGRect(x: margin, y: 712, width: 120, height: 20), size: 12,
color: navy, weight: .bold)
pill("timeout", x: 150, y: 707, w: 82, color: blue)
pill("partial failure", x: 242, y: 707, w: 102, color: orange)
pill("best-effort", x: 354, y: 707, w: 92, color: green)
pill("idempotency", x: 456, y: 707, w: 90, color: purple)
endPage(ctx)
// 6 — Transactions and concurrency: concept first
beginPage(ctx, page: 6)
sectionTitle("4", "트랜잭션·동시성 — 개념부터", "데이터의 일관성을 지키는 작업 단위와, 동시에 실행되는 요청을 제어하는 방법", color: orange)
drawText("트랜잭션의 ACID", CGRect(x: margin, y: 126, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
let acid: [(String, String, NSColor)] = [
("A · Atomicity", "전부 성공하거나 전부 취소", orange),
("C · Consistency", "규칙을 만족하는 상태로 이동", green),
("I · Isolation", "동시 작업의 중간 상태를 서로 숨김", purple),
("D · Durability", "COMMIT된 결과는 장애 후에도 보존", blue),
]
for (i, a) in acid.enumerated() {
let x = margin + CGFloat(i % 2) * 260
let y = CGFloat(165 + (i / 2) * 84)
callout(a.0, a.1, rect: CGRect(x: x, y: y, width: 247, height: 68), color: a.2)
}
drawText("동시성 문제는 어떻게 생기나?", CGRect(x: margin, y: 352, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
node("요청 A", "status=OPEN 읽음", rect: CGRect(x: 48, y: 401, width: 116, height: 64), color: blue)
node("요청 B", "status=OPEN 읽음", rect: CGRect(x: 48, y: 500, width: 116, height: 64), color: purple)
node("둘 다 처리", "중복 마감·중복 메일", rect: CGRect(x: 250, y: 449, width: 130, height: 70), color: red)
arrow(CGPoint(x: 164, y: 433), CGPoint(x: 250, y: 471), color: blue)
arrow(CGPoint(x: 164, y: 532), CGPoint(x: 250, y: 497), color: purple)
callout("해결 ① 비관적 잠금", "SELECT ... FOR UPDATE로 먼저 행을 잠급니다. 명확하지만 잠금 대기와 deadlock을 관리해야 합니다.",
rect: CGRect(x: 408, y: 391, width: 143, height: 92), color: orange)
callout("해결 ② 조건부 갱신", "UPDATE ... WHERE status=OPEN 후 rowcount를 확인합니다. 상태 검사와 변경이 원자적으로 일어납니다.",
rect: CGRect(x: 408, y: 497, width: 143, height: 92), color: green)
callout("격리 수준과 잠금은 만능이 아님", "격리를 높이면 안전성은 커지지만 동시 처리량이 줄고 대기·교착 가능성이 커집니다. 업무 규칙에 맞는 최소 범위의 트랜잭션과 조건부 상태 전이가 실용적입니다.",
rect: CGRect(x: margin, y: 624, width: 507, height: 92), color: orange)
callout("COMMIT / ROLLBACK", "COMMIT은 변경 확정, ROLLBACK은 현재 트랜잭션의 미확정 변경 취소입니다. 외부 이메일 발송은 DB rollback으로 되돌릴 수 없다는 점도 중요합니다.",
rect: CGRect(x: margin, y: 720, width: 507, height: 72), color: red)
endPage(ctx)
// 7 transaction concept
beginPage(ctx, page: 7)
sectionTitle("4", "DB 트랜잭션과 동시성 제어", "여러 작업을 하나로 묶고, 동시에 온 요청 중 한 명만 통과시키는 기술", color: orange)
callout("트랜잭션이란?", "은행 이체에서 ‘내 계좌 차감’과 ‘상대 계좌 증가’가 둘 다 성공하거나 둘 다 취소되어야 하듯, 관련 DB 변경을 하나의 작업 단위로 묶는 것입니다. 중간에 실패하면 rollback합니다.",
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: orange)
drawText("동시 마감 문제", CGRect(x: margin, y: 252, width: 200, height: 24),
size: 14, color: navy, weight: .bold)
node("사용자 클릭", "마감 요청 A", rect: CGRect(x: 50, y: 300, width: 110, height: 66), color: blue)
node("스케줄러", "마감 요청 B", rect: CGRect(x: 50, y: 405, width: 110, height: 66), color: purple)
node("조건부 UPDATE", "status != CLOSED", rect: CGRect(x: 243, y: 350, width: 120, height: 74), color: orange)
node("PostgreSQL", "원자적으로 판정", rect: CGRect(x: 430, y: 350, width: 112, height: 74), color: green)
arrow(CGPoint(x: 160, y: 333), CGPoint(x: 243, y: 376), color: blue)
arrow(CGPoint(x: 160, y: 438), CGPoint(x: 243, y: 399), color: purple)
arrow(CGPoint(x: 363, y: 387), CGPoint(x: 430, y: 387), color: orange)
callout("승자", "영향받은 행 수(rowcount) = 1\n마감 판정 권한 획득",
rect: CGRect(x: 76, y: 518, width: 205, height: 88), color: green)
callout("패자/재요청", "rowcount = 0\n이미 닫혔으므로 추가 처리 중단",
rect: CGRect(x: 314, y: 518, width: 205, height: 88), color: red)
comparison("단순 SELECT 후 UPDATE", "두 요청이 동시에 OPEN을 읽으면 둘 다 마감·낙찰 로직을 실행할 수 있습니다. 이메일도 두 번 발송될 수 있습니다.",
"조건부 UPDATE", "DB가 상태 검사와 변경을 한 문장으로 처리합니다. 먼저 성공한 요청만 rowcount=1을 받습니다.",
y: 640, color: orange)
endPage(ctx)
// 8 transaction code
beginPage(ctx, page: 8)
sectionTitle("4", "트랜잭션·동시성 — 실제 코드", "애플리케이션의 if문보다 DB의 원자적 UPDATE가 강한 최종 방어선입니다.", color: orange)
codeBox("조건부 상태 전이: 마감 권한 선점",
"negodata/backend/crud/quotation_crud.py · lines 482–500",
"""
query = (
update(quotations)
.where(
quotations.qt_id == qt_id,
quotations.status != QuotationStatus.CLOSED.value,
quotations.deleted == False,
)
.values(
status=QuotationStatus.CLOSED.value,
updated_at=GTime.UTC(),
)
)
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
""",
rect: CGRect(x: margin, y: 130, width: 507, height: 235), accent: orange)
codeBox("트랜잭션 실패 시 rollback",
"negodata/backend/common/database/db_session_manager.py · lines 116–127",
"""
try:
await db.commit()
return ErrorType.SUCCESS
except IntegrityError:
await db.rollback()
return ErrorType.DB_ALREADY_SAME_KEY
except Exception:
await db.rollback()
raise
""",
rect: CGRect(x: margin, y: 390, width: 507, height: 175), accent: red)
callout("왜 rowcount를 보나요?", "UPDATE가 에러 없이 실행됐다는 사실만으로는 내가 상태를 바꿨는지 알 수 없습니다. WHERE 조건에 맞는 행이 없으면 SQL은 정상 실행되지만 변경 행은 0개입니다. 그래서 1이면 승자, 0이면 이미 다른 요청이 처리한 것으로 판단합니다.",
rect: CGRect(x: margin, y: 592, width: 507, height: 108), color: orange)
callout("실무 체크", "트랜잭션은 짧게 유지하고, 외부 HTTP·이메일처럼 오래 걸리는 작업을 DB 트랜잭션 안에 오래 붙잡아 두지 않습니다.",
rect: CGRect(x: margin, y: 720, width: 507, height: 65), color: purple)
endPage(ctx)
// 9 — Multitenancy: concept first
beginPage(ctx, page: 9)
sectionTitle("5", "멀티테넌시 — 개념부터", "하나의 애플리케이션을 여러 고객사가 공유하면서 논리적으로 격리하는 설계", color: purple)
callout("Tenant란?", "서비스를 사용하는 독립 고객 단위입니다. 이 프로젝트에서는 주로 ‘회사’가 tenant입니다. 같은 API와 서버를 쓰더라도 회사별 데이터, 설정, 권한, 협상 정책이 섞이면 안 됩니다.",
rect: CGRect(x: margin, y: 126, width: 507, height: 88), color: purple)
drawText("대표적인 데이터 격리 모델", CGRect(x: margin, y: 242, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
callout("DB 분리", "회사마다 별도 DB\n격리 강함 · 운영비 높음",
rect: CGRect(x: margin, y: 282, width: 159, height: 88), color: blue)
callout("Schema 분리", "한 DB 안에서 schema 분리\n중간 수준의 격리와 비용",
rect: CGRect(x: 218, y: 282, width: 159, height: 88), color: cyan)
callout("Row 공유", "같은 테이블 + tenant_id\n효율적 · 쿼리 누락 위험",
rect: CGRect(x: 392, y: 282, width: 159, height: 88), color: orange)
drawText("격리는 DB만의 문제가 아닙니다", CGRect(x: margin, y: 404, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
let tenantAxes: [(String, String)] = [
("식별", "이 요청이 어느 회사 것인지 신뢰할 수 있게 결정"),
("인가", "그 사용자가 해당 회사 자원에 접근 가능한지 확인"),
("데이터", "모든 조회·수정 쿼리에 회사 범위 적용"),
("설정", "회사별 정책·브랜딩·카드 선택"),
("캐시", "캐시 key에 tenant를 포함해 회사 간 충돌 방지"),
("자원", "한 회사의 과부하가 다른 회사에 미치는 영향 제한"),
]
for (i, t) in tenantAxes.enumerated() {
let x = margin + CGFloat(i % 2) * 260
let y = CGFloat(444 + (i / 2) * 74)
rounded(CGRect(x: x, y: y, width: 247, height: 58), radius: 9,
fill: purple.withAlphaComponent(0.06), stroke: purple.withAlphaComponent(0.25))
drawText(t.0, CGRect(x: x + 12, y: y + 10, width: 52, height: 18), size: 10,
color: purple, weight: .bold)
drawText(t.1, CGRect(x: x + 66, y: y + 9, width: 168, height: 38), size: 8.5, color: ink)
}
callout("가장 흔한 사고", "쿼리의 WHERE tenant_id 조건 누락, 공유 캐시 key에 tenant_id 누락, 사용자가 body로 보낸 tenant_id를 그대로 신뢰하는 경우입니다. 그래서 tenant context를 요청 초기에 확정하고 자동 전달하는 구조가 중요합니다.",
rect: CGRect(x: margin, y: 680, width: 507, height: 105), color: red)
endPage(ctx)
// 10 multitenancy concept
beginPage(ctx, page: 10)
sectionTitle("5", "멀티테넌시", "하나의 시스템을 여러 회사가 쓰되, 설정과 데이터의 경계를 지키는 구조", color: purple)
callout("쉬운 비유", "한 오피스 빌딩을 여러 회사가 함께 사용하지만 출입카드가 자기 회사 층만 열어주는 구조입니다. 서버는 공유하되, 요청마다 ‘어느 회사의 요청인지’를 먼저 확정해야 합니다.",
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: purple)
drawText("요청이 회사별 엔진을 찾는 과정", CGRect(x: margin, y: 252, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
node("HTTP 요청", "X-Tenant-ID", rect: CGRect(x: 45, y: 310, width: 100, height: 68), color: blue)
node("Middleware", "존재·등록 검증", rect: CGRect(x: 195, y: 310, width: 105, height: 68), color: purple)
node("request.state", "tenant_id 보관", rect: CGRect(x: 350, y: 310, width: 105, height: 68), color: cyan)
arrow(CGPoint(x: 145, y: 344), CGPoint(x: 195, y: 344), color: blue)
arrow(CGPoint(x: 300, y: 344), CGPoint(x: 350, y: 344), color: purple)
node("Registry", "회사별 엔진 선택", rect: CGRect(x: 195, y: 445, width: 105, height: 68), color: orange)
node("TenantEngine", "회사별 정책·카드", rect: CGRect(x: 350, y: 445, width: 105, height: 68), color: green)
arrow(CGPoint(x: 402, y: 378), CGPoint(x: 275, y: 445), color: cyan)
arrow(CGPoint(x: 300, y: 479), CGPoint(x: 350, y: 479), color: orange)
callout("보안 핵심", "tenant_id를 요청 body에서 받으면 사용자가 다른 회사 ID를 넣어 위조할 수 있습니다. 이 프로젝트는 헤더/경로에서 결정한 값을 middleware가 request.state에 넣고, 뒤의 코드가 그것만 사용합니다.",
rect: CGRect(x: margin, y: 558, width: 507, height: 105), color: red)
comparison("멀티테넌시 경계가 약하면", "A회사 요청이 B회사 카드·설정·협상 엔진을 사용할 수 있습니다. 이는 단순 버그가 아니라 데이터 유출 사고입니다.",
"현재 방식", "요청 시작점에서 tenant를 검증하고, Registry가 해당 회사의 설정과 엔진을 해석합니다.",
y: 687, color: purple)
endPage(ctx)
// 11 multitenancy code
beginPage(ctx, page: 11)
sectionTitle("5", "멀티테넌시 — 실제 코드", "식별 → 검증 → request.state 전달 → 회사별 엔진 선택의 4단계", color: purple)
codeBox("Middleware: tenant를 요청 경계에서 확정",
"agent/router/middleware/tenant_middleware.py · lines 35–69",
"""
tenant_id = request.headers.get("X-Tenant-ID")
if not tenant_id:
return JSONResponse(status_code=400, ...)
if not tenant_registry.is_registered(tenant_id):
return JSONResponse(status_code=404, ...)
request.state.tenant_id = tenant_id
return await call_next(request)
""",
rect: CGRect(x: margin, y: 130, width: 507, height: 205), accent: purple)
codeBox("Dependency: 검증된 tenant로 엔진 조회",
"agent/router/deps.py · lines 13–21",
"""
async def get_tenant_engine(request: Request) -> TenantEngine:
tenant_id = getattr(request.state, "tenant_id", None)
if not tenant_id:
raise EXCEPTION_TENANT_HEADER_MISSING
return await tenant_registry.get_engine(tenant_id)
""",
rect: CGRect(x: margin, y: 360, width: 507, height: 165), accent: cyan)
codeBox("Registry: 프로세스 메모리에서 회사별 엔진 재사용",
"agent/tenancy/registry.py · lines 85–98",
"""
cached = self._engines.get(tenant_id)
if cached is not None:
return cached
async with self._locks[tenant_id]:
cached = self._engines.get(tenant_id)
if cached is not None:
return cached
engine = await self._build(tenant_id)
self._engines[tenant_id] = engine
return engine
""",
rect: CGRect(x: margin, y: 550, width: 507, height: 205), accent: orange)
endPage(ctx)
// 12 — Cache consistency: concept first
beginPage(ctx, page: 12)
sectionTitle("8", "캐시 정합성 — 개념부터", "비싼 계산·DB·외부 호출의 결과를 가까운 곳에 복사해 재사용하는 기술", color: red)
drawText("기본 용어", CGRect(x: margin, y: 126, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
let cacheTerms: [(String, String, NSColor)] = [
("Hit", "캐시에 값이 있어 원본을 읽지 않음", green),
("Miss", "값이 없어 원본을 읽고 캐시를 채움", blue),
("TTL", "값이 자동 만료될 때까지의 시간", orange),
("Stale", "원본은 바뀌었지만 캐시는 옛 값인 상태", red),
]
for (i, t) in cacheTerms.enumerated() {
let x = margin + CGFloat(i % 2) * 260
let y = CGFloat(165 + (i / 2) * 75)
callout(t.0, t.1, rect: CGRect(x: x, y: y, width: 247, height: 60), color: t.2)
}
drawText("대표적인 읽기·쓰기 패턴", CGRect(x: margin, y: 338, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
callout("Cache-aside", "앱이 캐시를 먼저 조회하고 miss이면 DB를 읽어 캐시에 저장합니다. 단순하고 가장 흔하지만 무효화를 앱이 책임집니다.",
rect: CGRect(x: margin, y: 378, width: 247, height: 92), color: blue)
callout("Write-through", "쓰기 때 캐시와 원본을 함께 갱신합니다. 읽기는 안정적이지만 쓰기 지연과 두 저장소의 부분 실패를 다뤄야 합니다.",
rect: CGRect(x: 304, y: 378, width: 247, height: 92), color: purple)
callout("Write-behind", "캐시에 먼저 쓰고 DB는 나중에 반영합니다. 빠르지만 캐시 장애 시 데이터 유실 위험이 있어 업무 원본에는 신중해야 합니다.",
rect: CGRect(x: margin, y: 486, width: 247, height: 92), color: orange)
callout("Negative cache", "‘결과 없음’도 잠깐 저장합니다. 반복 실패 비용을 줄이지만 너무 긴 TTL은 새로 생긴 데이터를 늦게 발견하게 합니다.",
rect: CGRect(x: 304, y: 486, width: 247, height: 92), color: green)
drawText("캐시에서 자주 생기는 문제", CGRect(x: margin, y: 610, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
callout("Invalidation", "원본 변경 후 어떤 key를 언제 삭제·갱신할지 결정하기 어렵습니다.",
rect: CGRect(x: margin, y: 650, width: 159, height: 82), color: red)
callout("Stampede", "인기 key가 만료되는 순간 많은 요청이 동시에 DB로 몰립니다.",
rect: CGRect(x: 218, y: 650, width: 159, height: 82), color: orange)
callout("Key 설계", "tenant·버전 등이 빠지면 서로 다른 데이터가 같은 key를 공유합니다.",
rect: CGRect(x: 392, y: 650, width: 159, height: 82), color: purple)
endPage(ctx)
// 13 cache concept
beginPage(ctx, page: 13)
sectionTitle("8", "캐시 정합성과 무효화", "빠른 복사본이 원본과 다른 값을 갖지 않도록 관리하는 문제", color: red)
callout("캐시는 복사본", "도서관 검색대의 메모가 캐시이고, 원본 장부가 DB라고 생각하면 쉽습니다. 메모는 빠르지만 오래된 정보일 수 있습니다. 정합성이란 메모와 장부가 의미상 같은 상태를 유지하는 것입니다.",
rect: CGRect(x: margin, y: 130, width: 507, height: 95), color: red)
drawText("앵커링 값의 저장·조회 순서", CGRect(x: margin, y: 252, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
node("1. DB 저장", "조정 이력 COMMIT", rect: CGRect(x: 46, y: 310, width: 118, height: 70), color: purple)
node("2. Redis SET", "최신값 + TTL 7일", rect: CGRect(x: 238, y: 310, width: 118, height: 70), color: red)
node("3. 다음 조회", "Redis 우선", rect: CGRect(x: 430, y: 310, width: 118, height: 70), color: blue)
arrow(CGPoint(x: 164, y: 345), CGPoint(x: 238, y: 345), color: purple)
arrow(CGPoint(x: 356, y: 345), CGPoint(x: 430, y: 345), color: red)
drawText("Redis 실패", CGRect(x: 240, y: 417, width: 110, height: 18), size: 9, color: red, weight: .bold)
arrow(CGPoint(x: 297, y: 380), CGPoint(x: 297, y: 465), color: red)
node("DB Fallback", "업무는 계속", rect: CGRect(x: 238, y: 465, width: 118, height: 70), color: green)
callout("stale 데이터란?", "DB에는 새 값 60이 저장됐는데 Redis SET이 실패해 캐시에 옛 값 55가 남은 상태입니다. 캐시 miss와 달리 값이 존재하므로 더 위험합니다. TTL과 주간 re-SET으로 회복합니다.",
rect: CGRect(x: margin, y: 574, width: 507, height: 95), color: orange)
comparison("캐시만 믿으면", "Redis 장애가 업무 장애가 되고, 오래된 값이 실제 제안가를 왜곡할 수 있습니다. Redis 유실 시 원본도 사라집니다.",
"원본 DB + 파생 캐시", "Redis 장애 시 DB를 읽고, TTL과 reconciliation으로 오래된 복사본을 교정합니다.",
y: 693, color: red)
endPage(ctx)
// 14 cache code
beginPage(ctx, page: 14)
sectionTitle("8", "캐시 정합성 — 실제 코드", "Cache-aside, TTL, DB fallback, reconciliation이 한 세트로 작동합니다.", color: red)
codeBox("Cache-aside: Redis miss → DB → Redis backfill",
"schedules/anchoring/src/anchoring/reader.py · lines 33–42",
"""
cached = await get_value(company_id, supplier_type, price_range)
if cached is not None:
return cached
value = await get_latest_adjusted_value(
db, company_id, supplier_type, price_range
)
if value is None:
value = get_base_anchoring_value(price_range)
await set_value(..., value, nx=True)
return value
""",
rect: CGRect(x: margin, y: 130, width: 507, height: 225), accent: red)
codeBox("Redis 장애는 cache miss로 취급",
"schedules/anchoring/src/anchoring/redis_client.py · lines 69–84",
"""
try:
raw = await _client.get(anchor_key(...))
if raw is None:
return None
return int(raw)
except Exception as ex:
_note_failure("get", anchor_key(...), ex)
return None # 호출측이 DB fallback
""",
rect: CGRect(x: margin, y: 380, width: 507, height: 180), accent: orange)
callout("두 겹의 회복 장치", "TTL 7일은 오래된 키가 영원히 남는 것을 막습니다. 주간 reconciliation은 DB의 최신 조정값을 Redis에 다시 SET하여, DB commit 뒤 Redis 갱신에 실패했던 값도 교정합니다.",
rect: CGRect(x: margin, y: 585, width: 507, height: 100), color: red)
callout("현재 견적 생성 경로의 예외", "Negodata의 실제 견적 생성은 Redis를 사용하지 않고 PostgreSQL의 anchoring.current_values View를 일괄 조회합니다. Redis는 현재 anchoring 배치 내부 캐시입니다.",
rect: CGRect(x: margin, y: 705, width: 507, height: 72), color: cyan)
endPage(ctx)
// 15 — Scheduler and batch: concept first
beginPage(ctx, page: 15)
sectionTitle("9", "스케줄러·배치 — 개념부터", "시간 규칙으로 작업을 시작하고, 많은 데이터를 사용자 요청 밖에서 처리하는 방식", color: green)
callout("둘의 차이", "스케줄러는 ‘언제 실행할지’를 결정합니다. 배치 Job은 ‘무엇을 어떻게 처리할지’를 구현합니다. CronTrigger가 알람시계라면 close_expired_quotations는 알람이 울렸을 때 수행할 실제 업무입니다.",
rect: CGRect(x: margin, y: 126, width: 507, height: 92), color: green)
drawText("Job의 생명주기", CGRect(x: margin, y: 248, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
node("Trigger", "실행 시각 도달", rect: CGRect(x: 45, y: 297, width: 94, height: 66), color: green)
node("Select", "처리 대상 조회", rect: CGRect(x: 181, y: 297, width: 94, height: 66), color: blue)
node("Process", "개별 업무 수행", rect: CGRect(x: 317, y: 297, width: 94, height: 66), color: orange)
node("Checkpoint", "결과·진행점 기록", rect: CGRect(x: 453, y: 297, width: 94, height: 66), color: purple)
arrow(CGPoint(x: 139, y: 330), CGPoint(x: 181, y: 330), color: green)
arrow(CGPoint(x: 275, y: 330), CGPoint(x: 317, y: 330), color: blue)
arrow(CGPoint(x: 411, y: 330), CGPoint(x: 453, y: 330), color: orange)
drawText("운영에서 반드시 결정할 것", CGRect(x: margin, y: 405, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
let jobIssues: [(String, String, NSColor)] = [
("중복 실행", "이전 Job이 안 끝났는데 다음 시각이 오면?", red),
("Misfire", "서버가 꺼져 실행 시각을 놓쳤다면?", orange),
("부분 실패", "100건 중 73번째가 실패하면 어디부터 재개?", purple),
("재시도", "즉시 재시도, 다음 tick, 운영자 재처리 중 무엇?", blue),
("멱등성", "같은 대상을 다시 처리해도 중복 효과가 없는가?", green),
("관측성", "처리량·실패 대상·소요시간을 로그와 지표로 남기는가?", cyan),
]
for (i, j) in jobIssues.enumerated() {
let x = margin + CGFloat(i % 2) * 260
let y = CGFloat(445 + (i / 2) * 73)
callout(j.0, j.1, rect: CGRect(x: x, y: y, width: 247, height: 58), color: j.2)
}
callout("스케줄러만으로 정확성은 보장되지 않음", "max_instances=1은 한 프로세스 안의 중복을 막을 뿐입니다. 서버가 여러 대면 각 서버가 Job을 실행할 수 있으므로 DB 조건부 갱신, 분산 락, 전용 Worker 같은 추가 방어가 필요합니다.",
rect: CGRect(x: margin, y: 680, width: 507, height: 105), color: red)
endPage(ctx)
// 16 scheduler concept
beginPage(ctx, page: 16)
sectionTitle("9", "스케줄러와 배치 안정성", "사용자 요청 없이 정해진 시간마다 반복 업무를 수행하는 백그라운드 실행", color: green)
callout("쉬운 비유", "API가 손님이 주문할 때 움직이는 직원이라면, 스케줄러는 매 5분마다 마감 시간이 지난 주문을 확인하는 당직자입니다. 사람이 요청하지 않아도 시간이 되면 일을 시작합니다.",
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: green)
drawText("5분 tick의 세 가지 작업", CGRect(x: margin, y: 252, width: 507, height: 24),
size: 14, color: navy, weight: .bold)
node("CronTrigger", "매 5분", rect: CGRect(x: 48, y: 315, width: 105, height: 68), color: green)
node("잡 ①", "기한 지난 견적 마감", rect: CGRect(x: 225, y: 280, width: 135, height: 62), color: orange)
node("잡 ②", "협상 완료 견적 마감", rect: CGRect(x: 225, y: 365, width: 135, height: 62), color: purple)
node("잡 ③", "LPS 결과 증분 반영", rect: CGRect(x: 225, y: 450, width: 135, height: 62), color: cyan)
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 311), color: green)
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 396), color: green)
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 481), color: green)
node("PostgreSQL", "조건부 처리·기록", rect: CGRect(x: 430, y: 365, width: 115, height: 72), color: blue)
arrow(CGPoint(x: 360, y: 311), CGPoint(x: 430, y: 385), color: orange)
arrow(CGPoint(x: 360, y: 396), CGPoint(x: 430, y: 401), color: purple)
arrow(CGPoint(x: 360, y: 481), CGPoint(x: 430, y: 420), color: cyan)
callout("중복 실행 방지 장치", "SCHEDULER_ENABLED=1인 프로세스 하나만 잡을 등록합니다. 각 잡은 max_instances=1이고, 밀린 실행은 coalesce=True로 한 번만 실행합니다. 그래도 다중 서버 가능성을 고려해 DB의 조건부 UPDATE가 마지막 방어선입니다.",
rect: CGRect(x: margin, y: 565, width: 507, height: 115), color: green)
comparison("안정 장치가 없으면", "서버 Worker 수만큼 같은 잡이 실행되고, 같은 견적을 여러 번 마감하거나 알림을 중복 발송할 수 있습니다.",
"현재 방식", "실행 프로세스 제한 + 잡 중복 제한 + DB 동시성 가드를 겹쳐 사용합니다.",
y: 704, color: green)
endPage(ctx)
// 17 scheduler code
beginPage(ctx, page: 17)
sectionTitle("9", "스케줄러·배치 — 실제 코드", "‘언제 실행할지’와 ‘무엇을 안전하게 처리할지’를 분리합니다.", color: green)
codeBox("APScheduler 등록: 5분, 중복 방지, 지연 허용",
"negodata/backend/scheduler/__init__.py · lines 37–69",
"""
_scheduler = AsyncIOScheduler(timezone="Asia/Seoul")
_scheduler.add_job(
jobs.close_expired_quotations,
CronTrigger(minute="*/5"),
id="close_expired_quotations",
coalesce=True, # 밀린 실행은 1번만
misfire_grace_time=600, # 10분 내 지연 실행 허용
max_instances=1, # 같은 잡 동시 실행 금지
)
""",
rect: CGRect(x: margin, y: 130, width: 507, height: 215), accent: green)
codeBox("Job: 대상 조회와 개별 마감 처리를 분리",
"negodata/backend/scheduler/jobs.py · lines 39–61",
"""
err_type, qt_ids = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(),
DBWRType.DB_READ.value,
lambda s: crud.list_due_for_close(s, now),
)
if err_type != ErrorType.SUCCESS:
return 0
results = await _close_each(service, qt_ids)
return sum(results.values())
""",
rect: CGRect(x: margin, y: 370, width: 507, height: 190), accent: cyan)
callout("멱등성(idempotency)", "같은 잡을 두 번 실행해도 최종 결과가 한 번 실행한 것과 같도록 만드는 성질입니다. 대상 조회가 중복될 수 있어도 claim_for_close의 조건부 UPDATE가 두 번째 처리를 rowcount=0으로 막습니다.",
rect: CGRect(x: margin, y: 585, width: 507, height: 105), color: purple)
callout("실패한 tick은 어떻게 되나요?", "LPS 동기화는 watermark 기반 증분 처리라 실패한 회차의 데이터가 다음 5분 tick에서 다시 대상이 됩니다. 스케줄러 자체 재시도보다 데이터 설계를 통해 회복합니다.",
rect: CGRect(x: margin, y: 710, width: 507, height: 72), color: green)
endPage(ctx)
// 18 combined scenario
beginPage(ctx, page: 18)
drawText("다섯 기술이 한 장면에서 만나는 순간", CGRect(x: margin, y: 48, width: 507, height: 34),
size: 23, color: navy, weight: .bold)
drawText("예: 협상이 모두 끝난 견적을 스케줄러가 자동 마감하는 동안 담당자가 수동 마감을 클릭했다.",
CGRect(x: margin, y: 88, width: 507, height: 30), size: 10.5, color: muted)
let rows: [(String, String, NSColor)] = [
("1", "멀티테넌시: 요청의 X-Tenant-ID로 어느 회사의 협상 엔진과 데이터인지 결정", purple),
("2", "분산 시스템: Backend가 Agent를 HTTP로 호출할 때 timeout과 부분 실패를 구분", blue),
("3", "스케줄러: 5분 tick이 동일 견적을 마감 대상으로 발견", green),
("4", "동시성 제어: 수동 요청과 스케줄러 중 조건부 UPDATE를 먼저 성공한 쪽만 처리", orange),
("5", "트랜잭션: 관련 상태 변경을 commit하거나, 실패하면 rollback", cyan),
("6", "캐시 정합성: 원본 DB commit 후 파생 캐시를 갱신하고 실패 시 다음 회차에 회복", red),
]
for (i, item) in rows.enumerated() {
let y = CGFloat(145 + i * 91)
rounded(CGRect(x: margin, y: y, width: 507, height: 70), radius: 12,
fill: item.2.withAlphaComponent(0.08), stroke: item.2.withAlphaComponent(0.30))
rounded(CGRect(x: 58, y: y + 15, width: 40, height: 40), radius: 20,
fill: item.2, stroke: nil)
drawText(item.0, CGRect(x: 58, y: y + 24, width: 40, height: 20), size: 13,
color: .white, weight: .bold, align: .center)
drawText(item.1, CGRect(x: 116, y: y + 15, width: 415, height: 42), size: 10.2,
color: ink, weight: .medium, lineSpacing: 3)
if i < rows.count - 1 {
arrow(CGPoint(x: 78, y: y + 70), CGPoint(x: 78, y: y + 90), color: item.2)
}
}
callout("핵심 관점", "어려운 백엔드 기술은 ‘라이브러리 이름’보다 경계와 실패를 다루는 방법입니다. 네트워크 경계, 회사 경계, 트랜잭션 경계, 캐시의 원본 경계를 명확하게 설계하는 것이 핵심입니다.",
rect: CGRect(x: margin, y: 708, width: 507, height: 78), color: navy)
endPage(ctx)
// 19 glossary
beginPage(ctx, page: 19)
drawText("초보자를 위한 한 줄 사전", CGRect(x: margin, y: 48, width: 507, height: 34),
size: 24, color: navy, weight: .bold)
let glossary: [(String, String)] = [
("분산 시스템", "여러 프로세스·서버가 네트워크로 협력하는 시스템"),
("부분 실패", "전체 중 일부 서비스만 실패한 상태"),
("Timeout", "응답을 무한히 기다리지 않고 정해진 시간에 포기하는 제한"),
("Best-effort", "실패해도 핵심 업무는 성공시키는 보조 작업 정책"),
("트랜잭션", "여러 DB 변경을 모두 성공 또는 모두 취소하는 작업 단위"),
("Rollback", "실패했을 때 트랜잭션의 변경을 되돌리는 것"),
("Race condition", "실행 순서에 따라 결과가 달라지는 동시성 문제"),
("원자적 연산", "중간 상태가 보이지 않도록 한 번에 처리되는 연산"),
("멀티테넌시", "한 시스템을 여러 고객사가 격리된 상태로 공유하는 구조"),
("Cache-aside", "캐시를 먼저 보고, miss이면 원본 조회 후 캐시를 채우는 패턴"),
("TTL", "캐시 값이 자동 만료되기까지의 시간"),
("Stale", "원본보다 오래되어 현재와 맞지 않는 캐시 상태"),
("Invalidation", "원본 변경 시 캐시를 삭제하거나 무효화하는 것"),
("Reconciliation", "원본과 복사본을 비교·재적재해 다시 맞추는 작업"),
("Scheduler", "정해진 시간 규칙에 따라 작업을 실행하는 도구"),
("Batch", "사용자 요청과 별개로 데이터 묶음을 주기적으로 처리하는 작업"),
("멱등성", "같은 작업을 반복해도 최종 결과가 달라지지 않는 성질"),
]
for (i, g) in glossary.enumerated() {
let col = i < 9 ? 0 : 1
let row = col == 0 ? i : i - 9
let x = margin + CGFloat(col) * 260
let y = CGFloat(128 + row * 69)
drawText(g.0, CGRect(x: x, y: y, width: 230, height: 19), size: 10.5,
color: [blue, orange, purple, red, green][i % 5], weight: .bold)
drawText(g.1, CGRect(x: x, y: y + 23, width: 230, height: 36), size: 8.8,
color: ink, lineSpacing: 2)
}
callout("추천 복습 순서", "트랜잭션·동시성 → 캐시 정합성 → 스케줄러 → 멀티테넌시 → 분산 시스템 순으로 다시 보면, 작은 DB 작업에서 전체 서비스 구조로 이해가 확장됩니다.",
rect: CGRect(x: margin, y: 718, width: 507, height: 74), color: blue)
endPage(ctx)
ctx.closePDF()
print(outPath)
-3
View File
@@ -57,8 +57,6 @@ export interface RefreshTokenResponse {
export interface Branding {
service_name?: string
logo_url?: string
primary_color?: string
email_header?: string
helpdesk?: string[] // 헬프데스크 연락처 — 한 줄 = 담당자 한 명. 비면 연락처 영역을 렌더하지 않는다
}
@@ -67,7 +65,6 @@ export interface SessionBrandingResponse {
result: ApiResult
service_name: string
logo_url: string
primary_color: string
helpdesk?: string[]
}
@@ -62,6 +62,7 @@ export interface SessionListItem {
renegotiation_status: number // 1=심사대기 2=승인 3=반려 4=철회, 이력 없으면 0
renegotiation_memo: string // 담당자 심사 메모(반려 사유)
result: number // 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
has_chat: boolean // 대화 이력 존재 여부 — 종료된 협상의 '결과 보기' 노출 판단용
}
/** 공급사 관점 협상 결과 (sessions 파생) */
@@ -118,10 +119,13 @@ export interface ParticipateResponse {
}
// --- 거부 (POST /v1/negotiation/sessions/{id}/reject) ---------------------
// 목록의 협상 거부와 채팅 중 협상 거부가 같은 엔드포인트를 쓴다.
// reject_reason: 프리셋(단종/품절) 라벨 또는 '기타' 직접 입력 텍스트.
// (백엔드 sessions.reject_reason 컬럼에 대응. 엔드포인트는 백엔드 추가 예정)
// reject_price/opinion: 채팅 중 거부에서만 채운다(목록 거부는 사유만).
export interface RejectRequest {
reject_reason: string
reject_price?: number
opinion?: string
}
export interface RejectResponse {
@@ -43,7 +43,6 @@ export function usePreLoginBranding(): Branding | null {
const next: Branding = {
service_name: res.service_name || undefined,
logo_url: res.logo_url || undefined,
primary_color: res.primary_color || undefined,
helpdesk: res.helpdesk?.length ? res.helpdesk : undefined,
}
if (!next.service_name && !next.logo_url && !next.helpdesk) return
@@ -1,10 +1,33 @@
import { useState } from 'react'
import { SessionStatus } from '@/apis'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
import { ChatMessage } from '@/features/chat/components/ChatMessage'
import { UserButton } from '@/features/chat/components/UserButton'
import { RejectPopup } from '@/features/chat/components/popup/RejectPopup'
import { canRejectNegotiation, GO_TO_LIST_TEXT } from '@/features/chat/lib/userButtonConfig'
import { MobileStepBar } from '@/features/chat/components/MobileStepBar'
import type { UserButtonConfig } from '@/features/chat/types'
// 미참여·협상거부로 끝난 세션은 '결과 보기'(열람) 진입이라 입력을 잠근다.
// 마지막 봇 메시지가 입력을 요구하는 상태로 멈춰 있어도(중간 이탈) 서버가 전송을 막으므로 액션바는 복귀 버튼만 둔다.
const READ_ONLY_STATUSES: number[] = [SessionStatus.NOT_PARTICIPATED, SessionStatus.REJECTED]
const READ_ONLY_CONFIG: UserButtonConfig = { type: 'one-black', text: GO_TO_LIST_TEXT }
// 거부 가능한 세션 상태 — 백엔드 /reject 가 허용하는 범위(완료/미참여/거부는 불가)와 같다.
const REJECTABLE_STATUSES: number[] = [SessionStatus.CREATED, SessionStatus.IN_PROGRESS]
export function ChatSection() {
const { userButtonConfig } = useChatStore()
const { messages, userButtonConfig } = useChatStore()
const sessionStatus = useChatInitStore((s) => s.session_status)
const [isRejectOpen, setIsRejectOpen] = useState(false)
const isReadOnly = READ_ONLY_STATUSES.includes(sessionStatus)
const config = isReadOnly ? READ_ONLY_CONFIG : userButtonConfig
// 단종·품절처럼 대화로 풀 수 없는 사유는 봇의 결렬 선언을 기다릴 수 없다 — 진행 중에도 빠져나갈 길을 둔다.
const canReject =
!isReadOnly && REJECTABLE_STATUSES.includes(sessionStatus) && canRejectNegotiation(messages, userButtonConfig)
return (
<div className="flex flex-1 flex-col w-full h-full min-h-0 bg-surface">
<MobileStepBar />
@@ -12,8 +35,9 @@ export function ChatSection() {
{/* 하단 액션 덱 */}
{/* safe-b: 홈 인디케이터에 입력 버튼이 가리지 않도록 하단 안전영역 확보 */}
<div className="shrink-0 safe-b border-t border-border bg-white shadow-[0_-4px_20px_rgba(0,0,0,0.03)]">
<UserButton {...userButtonConfig} />
<UserButton {...config} onReject={canReject ? () => setIsRejectOpen(true) : undefined} />
</div>
{isRejectOpen && <RejectPopup onClose={() => setIsRejectOpen(false)} />}
</div>
)
}
@@ -110,7 +110,8 @@ function ItemInfo() {
<div className="flex flex-1 items-start self-stretch overflow-y-auto overflow-x-hidden px-6 min-h-0">
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
{renderRow(fieldLabel('item.code', '상품코드'), item_code)}
{renderRow(fieldLabel('item.price', '단가'), formattedPrice)}
{/* 값은 회사가 고른 협상 기준가(item_price), 호칭은 공급사 화면 고정 용어 — 회사 용어 사전을 타지 않는다. */}
{renderRow('공급가', formattedPrice)}
{renderRow(fieldLabel('item.model_name', '모델명'), item_model_name)}
{renderRow(fieldLabel('item.manufacturer', '제조사'), item_maker_name)}
{renderRow(fieldLabel('item.moq', '최소주문수량'), item_min_order_quantity)}
@@ -17,7 +17,8 @@ const style = {
'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-white hover:bg-neutral-10 rounded-xl items-center justify-center text-sm font-bold text-neutral-80 border border-border cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
}
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
// onReject: 협상 거부 진입점. 넘어오면 버튼 덱 끝에 붙는다(입력 단계는 인풋이 넓어 좁은 화면에서 아랫줄로 wrap).
export function UserButton({ type, text, textList, priceErrorMessage, onReject }: UserButtonConfig & { onReject?: () => void }) {
if (type === '') return null
// 부가정보 입력은 폼이라 가운데정렬 덱이 아니라 전체폭으로 편다. text = 저장 후 보낼 동의 문구.
@@ -41,8 +42,13 @@ export function UserButton({ type, text, textList, priceErrorMessage }: UserButt
// 입력 단계는 에러 말풍선이 위로 삐져나가야 해서 overflow 클리핑 제외 (버튼 덱만 가로 스크롤 허용)
const isInputStep = type === 'percent' || type === 'price'
return (
<div className={cn('flex w-full justify-center px-6 py-4 max-[1180px]:px-4', !isInputStep && 'overflow-x-auto')}>
<div className="flex justify-center">
<div
className={cn(
'relative flex w-full flex-wrap items-center justify-center gap-3 px-6 py-4 max-[1180px]:px-4',
!isInputStep && 'overflow-x-auto',
)}
>
<div className="flex items-center justify-center gap-3">
{type === 'one-black' && <OneBlack text={text || '확인'} />}
{type === 'one-gray' && <OneGray text={text || '확인'} />}
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
@@ -53,6 +59,19 @@ export function UserButton({ type, text, textList, priceErrorMessage }: UserButt
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
{type === 'loading' && <LoadingDots />}
</div>
{/* 오클릭 방지: 주 CTA 와 붙이지 않는다. 넓은 화면은 우측 끝 고정(가운데 CTA 는 그대로),
좁은 화면은 인풋 폭 때문에 같은 줄이 안 나오므로 wrap 되어 아랫줄로 내려간다. */}
{onReject && (
<button
className={cn(
style.white,
'min-[1180px]:absolute min-[1180px]:right-8 min-[1180px]:top-1/2 min-[1180px]:-translate-y-1/2',
)}
onClick={onReject}
>
협상 거부
</button>
)}
</div>
)
}
@@ -0,0 +1,210 @@
import { useState } from 'react'
import { useNavigate } from 'react-router'
import { X } from 'lucide-react'
import { Modal } from '@/components'
import { getApiErrorMessage, useRejectMutation } from '@/apis'
import { cn, toast } from '@/lib'
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
import { useChatStore } from '@/features/chat/stores/useChatStore'
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
const MAX_PRICE = 999999999999999
// 사유 목록은 목록 화면의 거부 팝업과 동일하게 맞춘다.
const REASONS = ['단종', '품절', '기타'] as const
// 협상 진행 중 거부 팝업 — 목록의 거부 팝업과 같은 어휘·같은 엔드포인트를 쓰고,
// 대화 중이라 이미 오간 가격이 있으므로 공급 희망 가격과 의견을 더 받는다.
export function RejectPopup({ onClose }: { onClose: () => void }) {
const navigate = useNavigate()
const reject = useRejectMutation()
const sessionId = useChatStore((s) => s.sessionId)
const itemVatYn = useChatInitStore((s) => s.item_vat_yn)
const isVAT = itemVatYn === 'VAT별도'
const [selectedReason, setSelectedReason] = useState<string | null>(null)
const [customReason, setCustomReason] = useState('')
const [price, setPrice] = useState('')
const [opinion, setOpinion] = useState('')
const [showError, setShowError] = useState(false)
const isEtcOpen = selectedReason === '기타'
const isPending = reject.isPending
const isSubmitDisabled = !selectedReason || (isEtcOpen && !customReason.trim()) || isPending
const handleReasonClick = (reason: string) => {
setShowError(false)
if (selectedReason === reason) {
setSelectedReason(null)
setCustomReason('')
} else {
setSelectedReason(reason)
if (reason !== '기타') setCustomReason('')
}
}
const handlePriceChange = (value: string) => {
const numeric = value.replace(/\D/g, '')
if (numeric && parseInt(numeric) > MAX_PRICE) return
setPrice(numeric)
}
const handleSubmit = () => {
if (isEtcOpen && !customReason.trim()) {
setShowError(true)
return
}
if (isSubmitDisabled || !selectedReason) return
reject.mutate(
{
sessionId,
request: {
reject_reason: isEtcOpen ? customReason.trim() : selectedReason,
// 선택 입력 — 빈 값이면 보내지 않아 컬럼을 건드리지 않는다.
...(price ? { reject_price: parseInt(price) } : {}),
...(opinion.trim() ? { opinion: opinion.trim() } : {}),
},
},
{
onSuccess: () => {
onClose()
toast.warning('협상 거부가 완료되었습니다.')
navigate('/list')
},
onError: (error) => toast.error(getApiErrorMessage(error, '거부 처리에 실패했습니다.')),
},
)
}
const koreanPrice = price && parseInt(price) > 0 ? `[${numberToKorean(parseInt(price))} 원]` : ''
return (
<Modal onClose={onClose}>
<div className="flex max-h-[85vh] w-full max-w-md flex-col overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
{/* 헤더 */}
<div className="flex shrink-0 items-center justify-between border-b border-border p-5">
<h3 className="text-base font-bold text-neutral-90">거부 사유를 입력해주세요</h3>
<button
type="button"
onClick={onClose}
aria-label="닫기"
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
>
<X className="size-4" />
</button>
</div>
{/* 본문 */}
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-5">
<div className="grid grid-cols-3 gap-2">
{REASONS.map((reason) => (
<button
key={reason}
type="button"
onClick={() => handleReasonClick(reason)}
disabled={isPending}
className={cn(
'h-11 rounded-xl border text-sm font-bold transition-all active:scale-[0.98] disabled:opacity-50',
selectedReason === reason
? 'border-brand-600 bg-brand-light text-brand-600'
: 'border-border bg-white text-neutral-70 hover:bg-neutral-10',
)}
>
{reason}
</button>
))}
</div>
{isEtcOpen && (
<div className="animate-fade-in">
<textarea
placeholder="사유를 입력하여 주십시오"
value={customReason}
onChange={(e) => {
setCustomReason(e.target.value)
setShowError(false)
}}
rows={3}
disabled={isPending}
className={cn(
'w-full resize-none rounded-xl border bg-white p-3 text-sm text-neutral-90 outline-none transition-all',
'placeholder:text-neutral-50 focus:ring-1',
showError
? 'border-destructive focus:border-destructive focus:ring-destructive'
: 'border-border focus:border-brand-600 focus:ring-brand-600',
)}
/>
{showError && <p className="mt-1.5 text-xs font-medium text-destructive">기타 사유를 입력해주세요</p>}
</div>
)}
{/* 공급 희망 가격 (선택) — 결렬 폼과 같은 라벨·표기 */}
<div className="flex flex-col gap-1.5">
<div className="text-sm font-bold text-neutral-90">
공급 희망 가격 <span className="font-medium text-neutral-60">(선택)</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<input
type="text"
className={cn(
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
isPending
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
)}
value={price ? parseInt(price).toLocaleString() : ''}
onChange={(e) => handlePriceChange(e.target.value)}
placeholder="0"
disabled={isPending}
/>
<span className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</span>
{koreanPrice && <span className="whitespace-nowrap text-sm text-neutral-50">{koreanPrice}</span>}
</div>
</div>
{/* 의견 (선택) — 결렬 폼과 동일 */}
<div className="flex flex-col gap-1.5">
<div className="text-sm font-bold text-neutral-90">
의견 <span className="font-medium text-neutral-60">(선택)</span>
</div>
<textarea
value={opinion}
onChange={(e) => setOpinion(e.target.value)}
rows={2}
maxLength={255}
disabled={isPending}
placeholder="추가로 남길 의견이 있으면 작성해 주세요."
className={cn(
'w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
isPending
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
)}
/>
</div>
</div>
{/* 푸터 — 목록 거부 팝업과 동일 규격 */}
<div className="flex shrink-0 gap-2 border-t border-border p-4">
<button
type="button"
onClick={onClose}
disabled={isPending}
className="h-11 flex-1 rounded-xl border border-border bg-white text-sm font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98] disabled:opacity-50"
>
취소
</button>
<button
type="button"
onClick={handleSubmit}
disabled={isSubmitDisabled}
className="h-11 flex-1 rounded-xl bg-brand-600 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-40"
>
거부 처리
</button>
</div>
</div>
</Modal>
)
}
@@ -24,8 +24,9 @@ const TERMINAL_CODES = new Set<number>([
ErrorCode.NEGO_NOT_FOUND,
])
// 진입 로드(init/messages) 시 '잘못된 접근'으로 볼 코드 → 권한 없음 / 없는(또는 남의) 세션 /
// 진입 불가 상태(미참여·거부). 토스트 안내 후 목록으로 복귀시킨다. (인증≠인가 — 로그아웃하지 않는다)
// 진입 로드(init/messages) 시 '잘못된 접근'으로 볼 코드 → 권한 없음 / 없는(또는 남의) 세션 / 진입 불가 상태.
// 토스트 안내 후 목록으로 복귀시킨다. (인증≠인가 — 로그아웃하지 않는다)
// 종료된 세션(완료·미참여·거부)은 열람 진입이 허용되므로 여기 걸리지 않는다 — 입력만 잠긴다(ChatSection).
const INVALID_ACCESS_CODES = new Set<number>([
ErrorCode.NEGO_FORBIDDEN,
ErrorCode.NEGO_NOT_FOUND,
@@ -115,8 +116,8 @@ export function useChatController(sessionId: string) {
if (data.message) s.appendMessage(mapMessage(data.message))
s.setIsLoading(false)
// 협상 종료 전이(완료/거부 등): 목록 캐시만 무효화해 /list 복귀 시 최신 상태를 보장한다.
// init 은 '진입 메타'라 화면에서 재조회하지 않는다 — 재조회하면 미참여/거부 진입 게이트(1301)에
// 걸려 방금 정상 종료한 사용자가 튕겨난다. 재진입 시 최신 status 는 언마운트의 removeQueries 가 보장한다.
// init 은 '진입 메타'라 화면에서 재조회하지 않는다 — 방금 종료한 화면의 입력이 열람 모드로
// 갈아치워지지 않게 한다. 재진입 시 최신 status 는 언마운트의 removeQueries 가 보장한다.
if (data.session_status !== SessionStatus.IN_PROGRESS || data.message?.chat_end) {
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
}
@@ -2,6 +2,17 @@ import type { ChatMessage, UserButtonConfig } from '@/features/chat/types'
export const GO_TO_LIST_TEXT = '상품 목록으로 가기'
// 협상 거부 진입점을 숨기는 액션바 상태.
// reject=봇이 이미 결렬을 선언(그 폼이 최종가를 받는다) / extra-info=타결 후 동의 단계 / loading=응답 대기.
const NO_REJECT_TYPES = ['', 'loading', 'reject', 'extra-info']
// 채팅 안에서 협상을 거부할 수 있는 상태인지 — 대화가 끝나지 않고 협력사 입력을 기다리는 동안만.
export function canRejectNegotiation(messages: ChatMessage[], config: UserButtonConfig): boolean {
if (!messages || messages.length === 0) return false
if (messages[messages.length - 1].chat_end) return false
return !NO_REJECT_TYPES.includes(config.type)
}
// 마지막 봇 메시지의 next_input_mode 로 하단 입력 UI 구성을 결정한다.
export function deriveUserButtonConfig(
messages: ChatMessage[],
@@ -29,7 +29,7 @@ export function GuidePopup({ onClose }: { onClose: () => void }) {
<Row badge="협상 중" tone="prog" text="가격을 조율하는 중입니다. 이어서 진행하세요." />
<Row badge="협상 완료" tone="done" text="가격 제출을 마쳤습니다. 최종 결과는 견적 마감 후 아래 '결과'로 표시됩니다." />
<Row badge="협상 미참여" tone="none" text="기한 내 참여하지 않아 종료된 건입니다." />
<Row badge="협상 거절" tone="reject" text="내가 참여를 거절한 건입니다." />
<Row badge="협상 거부" tone="reject" text="내가 거부한 건입니다." />
</Section>
<Section title="협상 결과" desc="견적이 마감된 뒤 정해지는 낙찰 결과입니다. 마감 전에는 표시되지 않습니다.">
@@ -2,7 +2,7 @@ import { Loader2, MessageSquareText } from 'lucide-react'
import { cn, formatKstDateTime } from '@/lib'
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
import type { ListItem } from '@/features/list/types'
import { statusMeta, RESULT_META } from '@/features/list/lib/status'
import { statusMeta, canEnterChat, isEndedStatus, RESULT_META } from '@/features/list/lib/status'
interface WorkspaceCardsProps {
items: ListItem[]
@@ -55,10 +55,11 @@ function Card({
onMemo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const ended = isEndedStatus(item.session_status)
const canEnter = canEnterChat(item.session_status, item.hasChat)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
const enterLabel = ended ? '결과 보기' : '협상 입장'
// 재협상: 요청 가능하면 버튼, 이미 요청했으면 진행 상태를 보여준다.
const renegoLabel = RENEGO_STATUS_LABEL[item.renegotiationStatus] ?? ''
@@ -138,7 +139,7 @@ function Card({
onClick={() => onReject(item)}
className="flex-1 rounded-lg border border-border py-2 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
>
거절
협상 거부
</button>
)}
{canEnter && (
@@ -3,7 +3,7 @@ import { Loader2, MessageSquareText } from 'lucide-react'
import { cn, formatKstDateTime } from '@/lib'
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
import type { ListItem } from '@/features/list/types'
import { statusMeta, RESULT_META } from '@/features/list/lib/status'
import { statusMeta, canEnterChat, isEndedStatus, RESULT_META } from '@/features/list/lib/status'
interface WorkspaceTableProps {
items: ListItem[]
@@ -73,10 +73,11 @@ function Row({
onMemo: (item: ListItem) => void
}) {
const meta = statusMeta(item.session_status)
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
const ended = isEndedStatus(item.session_status)
const canEnter = canEnterChat(item.session_status, item.hasChat)
const canReject = ['협상생성', '협상중'].includes(item.session_status)
const isDone = item.session_status === '협상완료'
const enterLabel = isDone ? '결과 보기' : '협상 입장'
const enterLabel = ended ? '결과 보기' : '협상 입장'
return (
<tr className="border-b border-border/60 transition-colors last:border-0 hover:bg-table-hover/70">
@@ -150,7 +151,7 @@ function Row({
onClick={() => onReject(item)}
className="rounded-lg border border-border px-3 py-1.5 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
>
거절
협상 거부
</button>
)}
{canEnter ? (
@@ -24,6 +24,7 @@ import { ExtraInfoPopup } from '@/features/list/components/ExtraInfoPopup'
import { RenegotiationPopup } from '@/features/list/components/RenegotiationPopup'
import { RenegotiationMemoPopup } from '@/features/list/components/RenegotiationMemoPopup'
import { GuidePopup } from '@/features/list/components/GuidePopup'
import { isEndedStatus } from '@/features/list/lib/status'
import type { ListItem } from '@/features/list/types'
// 상태별 거부 불가 안내
@@ -70,6 +71,11 @@ export function ListWorkspace() {
const [guideOpen, setGuideOpen] = useState(false)
const handleEnter = (item: ListItem) => {
// 종료 건(완료·미참여·거부)은 열람 전용 — 참여 API 는 미참여/거부를 막으므로 바로 채팅으로 보낸다.
if (isEndedStatus(item.session_status)) {
navigate(`/chat?session_id=${item.session_id}`)
return
}
setEnteringId(item.session_id)
participate.mutate(item.session_id, {
onSuccess: () => navigate(`/chat?session_id=${item.session_id}`),
@@ -94,8 +100,8 @@ export function ListWorkspace() {
reject.mutate(
{ sessionId: rejectTarget.session_id, request: { reject_reason: reason } },
{
onSuccess: () => toast.warning('참여 거절이 완료되었습니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '거절 처리에 실패했습니다.')),
onSuccess: () => toast.warning('협상 거부가 완료되었습니다.'),
onError: (error) => toast.error(getApiErrorMessage(error, '거부 처리에 실패했습니다.')),
},
)
}
@@ -42,5 +42,6 @@ export function toListItem(api: SessionListItem): ListItem {
renegotiationStatus: api.renegotiation_status ?? 0,
renegotiationMemo: api.renegotiation_memo ?? '',
result: api.result ?? 0,
hasChat: api.has_chat ?? false,
}
}
+13 -1
View File
@@ -11,13 +11,25 @@ export const STATUS_META: Record<string, StatusMeta> = {
협상중: { display: '협상 중', badge: 'bg-[#FFF3E5] text-[#F5A623]', dot: 'bg-[#F5A623]' },
협상완료: { display: '협상 완료', badge: 'bg-[#EAFDF3] text-success', dot: 'bg-success' },
미참여: { display: '협상 미참여', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' },
협상거부: { display: '협상 거절', badge: 'bg-[#FFEBEB] text-[#FF4D4F]', dot: 'bg-[#FF4D4F]' },
협상거부: { display: '협상 거부', badge: 'bg-[#FFEBEB] text-[#FF4D4F]', dot: 'bg-[#FF4D4F]' },
}
export function statusMeta(label: string): StatusMeta {
return STATUS_META[label] ?? { display: label || '-', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' }
}
// 종료 상태 — 대화를 이어갈 수 없고 지난 이력만 '결과 보기'로 열람한다(백엔드 send 도 협상중만 허용).
const ENDED_STATUSES = ['협상완료', '미참여', '협상거부']
export function isEndedStatus(label: string): boolean {
return ENDED_STATUSES.includes(label)
}
// 채팅 진입 가능 여부. 진행 건은 항상, 종료 건은 볼 대화가 있을 때만 — 초청만 받고 끝난 건은 열어도 빈 화면이다.
export function canEnterChat(label: string, hasChat: boolean): boolean {
return !isEndedStatus(label) || hasChat
}
// 협상 결과(SessionResult 코드) → 완료 건에 붙는 결과 배지. 0(미정)은 표시하지 않는다.
// 결렬(3)은 재협상 요청 대상이라 눈에 띄게 노랑으로 둔다.
export const RESULT_META: Record<number, { label: string; badge: string }> = {
+1
View File
@@ -13,4 +13,5 @@ export type ListItem = {
renegotiationStatus: number // 0=없음 1=심사중 2=승인 3=반려 4=철회
renegotiationMemo: string // 담당자 심사 메모(반려 사유)
result: number // 협상 결과: 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
hasChat: boolean // 대화 이력 존재 — 종료된 협상의 '결과 보기' 노출 조건
}
+1 -1
View File
@@ -44,7 +44,7 @@ export function MainLayout({
header,
children,
}: MainLayoutProps) {
const { data: user } = useMeQuery() // 회사 브랜딩(서비스명/로고) 주입
const { data: user } = useMeQuery() // 회사 브랜딩(서비스명/로고) 주입 — 색은 솔루션 고정
const panes = (
<>
<aside className={cn(styles.sidebar, SIDEBAR_WIDTH[sidebarWidth])}>
+1 -1
View File
@@ -4,7 +4,7 @@ import { Logo } from '@/components'
import { LoginForm, usePreLoginBranding } from '@/features/auth'
export function LoginPage() {
// 초청 링크의 session_id(없으면 직전 로그인 캐시)로 회사 브랜딩을 먼저 그린다.
// 초청 링크의 session_id(없으면 직전 로그인 캐시)로 회사 브랜딩(서비스명·로고)을 먼저 그린다.
const branding = usePreLoginBranding()
// 이미 로그인된 상태면 목록으로
+23
View File
@@ -64,6 +64,22 @@ export interface RequeueRes {
requeued: boolean;
}
/** 몰별 확인 상태 — LPS common.enums.SourceState 와 1:1. 정의는 lps/docs/result-states.md. */
export type SourceState =
| "matched" // 수집·매칭 성공
| "no_match" // 수집됐으나 같은 상품이 아님
| "empty" // 검색 결과 자체가 0건
| "blocked" // 안티봇 차단 — IP 회전으로 자동 회복
| "env_blocked" // 회전 무효 — 사람이 환경/설정을 고쳐야 함
| "unavailable" // 전송 실패·가용 IP 없음 등 일시적
| "skipped"; // 그 소스를 쓰지 않음
export interface SourceInfo {
state: SourceState;
count?: number; // 수집 건수(성공 시)
error?: string; // 실패 사유 원문(운영 진단용)
}
export interface ProductItem {
product_code: string;
display_name?: string;
@@ -74,6 +90,10 @@ export interface ProductItem {
final_lowest?: number;
final_source?: string;
searches: number;
/** 몰별 확인 상태. 운영 화면은 원인까지 봐야 조치를 가른다(검색어 문제 vs IP·환경 문제). */
sources?: Record<string, SourceInfo>;
/** 못 본 몰이 있어 결과가 최종이 아님 */
partial?: boolean;
}
export interface ProductListRes {
@@ -105,6 +125,9 @@ export interface PricePoint {
coupang_name?: string;
coupang_url?: string;
by_mall?: MallEntry[];
/** 몰별 확인 상태. by_mall 은 가격이 있는 몰만 담으므로 '못 본 몰'은 여기에만 있다. */
sources?: Record<string, SourceInfo>;
partial?: boolean;
}
export interface PriceHistoryRes {
+62
View File
@@ -0,0 +1,62 @@
/**
* 몰별 확인 상태의 표기 — **운영자용**(상세). 정의는 lps/docs/result-states.md.
*
* 실사용자 화면(negodata)은 이걸 3가지로 접어서 보여준다. 여기서 접지 않는 이유는
* 운영자의 목적이 **진단**이기 때문이다: `blocked`(자동 회복)와 `env_blocked`(사람이 고쳐야 함)를
* 뭉뚱그리면 회복될 일에 매달리거나 손봐야 할 설정을 방치하게 된다.
*
* 색은 전부 index.css @theme 토큰을 참조한다(raw hex 금지 — 토큰을 바꾸면 여기도 함께 바뀌어야 함).
*/
import type { SourceState } from "../api/types";
type Meta = {
label: string;
color: string;
/** 한 줄 설명 — '이게 무슨 뜻이고 내가 뭘 해야 하나' */
desc: string;
/** 그 몰을 실제로 확인했는가. false 면 '없다'고 말하면 안 된다 */
confirmed: boolean;
};
export const SOURCE_STATES: Record<SourceState, Meta> = {
matched: {
label: "매칭", color: "var(--color-ok-600)", confirmed: true,
desc: "수집·매칭 성공 — 가격 확보",
},
no_match: {
label: "같은 상품 없음", color: "var(--color-neutral-400)", confirmed: true,
desc: "수집은 됐으나 같은 상품이 아님 — 검색어·규격을 의심할 것",
},
empty: {
label: "결과 0건", color: "var(--color-neutral-400)", confirmed: true,
desc: "그 몰의 검색 결과 자체가 0건 — 확인했고 정말 없다",
},
blocked: {
label: "차단", color: "var(--color-warn-600)", confirmed: false,
desc: "안티봇 차단 — IP 회전으로 자동 회복된다. 반복되면 IP 풀·예산 확인",
},
env_blocked: {
label: "환경 차단", color: "var(--color-dead-600)", confirmed: false,
desc: "회전해도 회복 불가 — 사람이 환경/게이트웨이 설정을 고쳐야 한다",
},
unavailable: {
label: "확인 못함", color: "var(--color-warn-600)", confirmed: false,
desc: "전송 실패·가용 IP 없음 등 일시적 — 잠시 후 재시도로 회복",
},
skipped: {
label: "미사용", color: "var(--color-neutral-300)", confirmed: true,
desc: "그 소스를 쓰지 않음(폴백 OFF 등)",
},
};
/** 미지의 상태도 화면을 깨뜨리지 않는다 — 값 그대로 보여주고 '모름'으로 취급한다. */
export const stateMeta = (s: string | undefined): Meta =>
SOURCE_STATES[s as SourceState] ?? {
label: s || "-", color: "var(--color-ink-400)", desc: "알 수 없는 상태", confirmed: false,
};
/** 못 본 몰 목록 — 결과가 왜 최종이 아닌지 한 줄로 설명할 때 쓴다. */
export const unconfirmedMalls = (sources?: Record<string, { state: string }>): string[] =>
Object.entries(sources ?? {})
.filter(([, v]) => !stateMeta(v?.state).confirmed)
.map(([mall]) => mall);
+47 -2
View File
@@ -6,7 +6,8 @@ import {
Area, CartesianGrid, ComposedChart, Line, ReferenceLine, ResponsiveContainer, Tooltip, XAxis, YAxis,
} from "recharts";
import { get, post } from "../api/client";
import type { PriceHistoryRes, PricePoint, ProductItem, ProductListRes, SearchRes } from "../api/types";
import type { PriceHistoryRes, PricePoint, ProductItem, ProductListRes, SearchRes, SourceInfo } from "../api/types";
import { stateMeta, unconfirmedMalls } from "../lib/sourceState";
import { Button, Card, Empty, ErrorNote, Legend, Loading, PageHeader, ScrollBox, ScrollTable, SearchForm, Segmented } from "../components/ui";
import { gridProps, xAxisProps, yAxisProps } from "../lib/chart";
import { dateShort, timeAgo, won } from "../lib/format";
@@ -83,7 +84,17 @@ export default function Products() {
</div>
<div className="mt-0.5 flex justify-between text-[11px] text-ink-400">
<span>{p.product_code} · 검색 {p.searches}회</span>
<span>{timeAgo(p.triggered_at)}{p.outcome === "not_found" ? " · 못 찾음" : ""}</span>
<span className="flex items-center gap-1">
{/* 못 본 몰이 있으면 이 값은 최종이 아니다 — 가격 옆에서 바로 보여야 오해가 없다 */}
{p.partial && (
<span className="rounded px-1 font-semibold text-warn-600"
style={{ background: "color-mix(in srgb, var(--color-warn-600) 12%, transparent)" }}
title={`확인 못한 몰: ${unconfirmedMalls(p.sources).join(", ")}`}>
일부 확인 못함
</span>
)}
{timeAgo(p.triggered_at)}{p.outcome === "not_found" ? " · 못 찾음" : ""}
</span>
</div>
</button>
</li>
@@ -215,6 +226,39 @@ const MALL_COLS = [
const srcColor = (s?: string) => s === "naver" ? "var(--color-naver)" : s === "coupang" ? "var(--color-coupang)" : "var(--color-ink-400)";
const srcLabel = (s?: string) => s === "naver" ? "네이버" : s === "coupang" ? "쿠팡" : (s || "기타");
/**
* 몰별 확인 상태 — 아래 가격표가 **왜 그렇게 생겼는지**를 설명한다.
* 가격표에 없는 몰이 '거기엔 없더라'인지 '거기를 못 봤다'인지는 이 줄에만 있다.
* 운영 화면이라 상태를 접지 않는다: blocked(자동 회복)와 env_blocked(사람이 고쳐야 함)는 조치가 다르다.
*/
function SourceStates({ sources, partial }: { sources?: Record<string, SourceInfo>; partial?: boolean }) {
const entries = Object.entries(sources ?? {});
if (entries.length === 0) return null; // 이 컬럼 추가 이전 이력 — 조용히 숨긴다
return (
<div className="mb-2 shrink-0 space-y-1 rounded border border-line-100 bg-surface-2 px-2 py-1.5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
{entries.map(([mall, info]) => {
const m = stateMeta(info?.state);
return (
<span key={mall} className="inline-flex items-center gap-1 text-[11px]"
title={`${m.desc}${info?.error ? `\n\n${info.error}` : ""}`}>
<span className="h-1.5 w-1.5 shrink-0 rounded-full" style={{ background: m.color }} aria-hidden />
<span className="font-semibold text-ink-500">{mall}</span>
<span style={{ color: m.color }}>{m.label}</span>
{info?.count != null && <span className="tnum text-ink-400">{info.count}건</span>}
</span>
);
})}
</div>
{partial && (
<p className="text-[11px] leading-snug text-warn-600">
{unconfirmedMalls(sources).join("·")} 을(를) 확인하지 못했습니다 — 이 최저가는 최종이 아닙니다.
</p>
)}
</div>
);
}
function MallCompare({ point }: { point: PricePoint }) {
const [topN, setTopN] = useState<number | "all">(5);
const malls = (point.by_mall ?? [])
@@ -230,6 +274,7 @@ function MallCompare({ point }: { point: PricePoint }) {
<p className="mb-1.5 shrink-0 text-[11px] text-ink-400">
<span className="tnum font-semibold text-ink-500">{dateShort(point.triggered_at)}</span> 기준 · 그래프의 시점을 클릭해 이동
</p>
<SourceStates sources={point.sources} partial={point.partial} />
{shown.length === 0 ? (
<div className="grid h-full place-items-center"><Empty>몰별 데이터 없음</Empty></div>
) : (
+2
View File
@@ -194,9 +194,11 @@ docker compose up -d # negosium 스택 + lps-api·lps-worker·lps
| 문서 | 대상 | 내용 |
|------|------|------|
| **[아키텍처](docs/architecture.md)** | 개발자/기획자 | 구성요소·파이프라인·안티봇(Akamai/Turnstile)·비용계측·동시성 |
| **[결과 상태 정의](docs/result-states.md)** | 개발자/기획자 | '못 찾음'과 '못 봄'의 구분 — 몰별·상품별 상태 정의와 화면 표기 매핑 |
| **[데이터베이스](docs/database.md)** | 개발자/기획자 | 테이블 6종 구조와 코드값(+by_mall·ip_session·proxy_port 장부) |
| **[API 사용법](docs/api.md)** | 연동 개발자 | 엔드포인트·요청/응답·metrics 예시 |
| **[운영 가이드](docs/operations.md)** | 운영자/개발자 | 실행·병렬·관측(readyz/ops/알림)·**Docker 배포**·문제 해결 |
| **[2026-08-07 세션 기록](docs/2026-08-07-session-notes.md)** | 팀 | 직전 작업 요약 — 결정 근거·미해결(쿠팡 차단)·다음 할 일·주의사항 |
| **[크롤러 논의](docs/decision-openmarket-crawler.md)** | 팀 | 오픈마켓 크롤러 유지 여부(ROI) 의사결정 메모 |
---
+10
View File
@@ -105,6 +105,16 @@ class price_history(MAIN_BASE):
# 몰별 최저가 스냅샷(열린 스키마) — [{mall, source, price, shipping_fee, shipping_type, url}, ...].
# 몰이 늘어도 컬럼 추가/마이그레이션 없이 담는다(G마켓·옥션·11번가 등). naver/coupang 3선은 위 컬럼 유지.
by_mall = Column(JSONB, nullable=True)
# ── 몰별 '확인했는가' ─────────────────────────────────────────────────────
# by_mall 은 **가격이 있는 몰만** 담는다. 그래서 어떤 몰이 빠졌을 때 '거기엔 없더라'인지
# '거기를 못 봤다'인지 알 수 없었다 — 안 본 걸 없다고 말하는 셈이었다.
# {"naver": {"state": "matched", "count": 40}, "coupang": {"state": "blocked", "error": "..."}}
# state 값은 common.enums.SourceState (정의·표기 규칙은 docs/result-states.md).
sources = Column(JSONB, nullable=True)
# 결과가 완전한가. True = 못 본 몰이 있어 이 값이 최종이 아니다.
# sources 에서 유도 가능하지만 컬럼으로 둔다 — 소비자가 '어떤 상태가 확인된 것인가'라는
# 판단 규칙까지 알아야 하면 상태 정의가 두 곳으로 흩어진다. 판단은 여기서 끝내고 사실만 넘긴다.
partial = Column(Boolean, nullable=False, server_default=text("false"))
created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
+23
View File
@@ -69,3 +69,26 @@ class JobType(Enum):
SEARCH = 1 # 최저가 검색(쿠팡=브라우저) — 무거움
OUTBOX = 2 # 외부 API 결과 전송(재시도 엔진 공유) — 가벼움
class SourceState(Enum):
"""한 상품을 **한 몰에서** 찾은 결과. 정의·표기 규칙은 docs/result-states.md 가 소스다.
가장 중요한 경계는 `확인함` 과 `못 봄` 사이다:
MATCHED·NO_MATCH·EMPTY 그 몰을 실제로 봤다 → "없다"고 말해도 되는 사실
BLOCKED·ENV_BLOCKED·UNAVAILABLE 못 봤다 → "없다"고 말하면 거짓이 된다
이 경계를 잃으면 '차단당해 못 본 것'이 '그 몰엔 없음'으로 둔갑한다(실측 문제).
"""
MATCHED = 1 # 수집·매칭 성공 — 가격 확보
NO_MATCH = 2 # 수집은 됐으나 같은 상품이 없음(액세서리·다른 규격만)
EMPTY = 3 # 그 몰의 검색 결과 자체가 0건
BLOCKED = 4 # 안티봇 차단 — IP 회전으로 회복 가능(자동)
ENV_BLOCKED = 5 # 회전해도 안 되는 차단(환경·게이트웨이 설정) — 사람이 고쳐야 함
UNAVAILABLE = 6 # 전송 실패·가용 IP 없음 등 일시적 — 잠시 후 재시도로 회복
SKIPPED = 7 # 그 소스를 아예 쓰지 않음(폴백 OFF 등)
@property
def confirmed(self) -> bool:
"""그 몰을 **실제로 확인했는지**. False 면 '없다'고 단정하면 안 된다."""
return self in (SourceState.MATCHED, SourceState.NO_MATCH, SourceState.EMPTY)
+10 -6
View File
@@ -13,6 +13,7 @@ _FIELDS = (
"coupang_lowest", "coupang_name", "coupang_url",
"final_lowest", "final_source", "final_rating", "final_review_count",
"final_shipping_fee", "final_shipping_type", "final_shipping_label",
"partial",
)
@@ -27,17 +28,20 @@ class PriceHistory:
naver_lowest, naver_name, naver_url,
coupang_lowest, coupang_name, coupang_url,
final_lowest, final_source, final_rating, final_review_count,
final_shipping_fee, final_shipping_type, final_shipping_label, by_mall)
final_shipping_fee, final_shipping_type, final_shipping_label,
by_mall, sources, partial)
VALUES
(:product_code, :job_id, :outcome, :matched_count,
:naver_lowest, :naver_name, :naver_url,
:coupang_lowest, :coupang_name, :coupang_url,
:final_lowest, :final_source, :final_rating, :final_review_count,
:final_shipping_fee, :final_shipping_type, :final_shipping_label, CAST(:by_mall AS jsonb))
:final_shipping_fee, :final_shipping_type, :final_shipping_label,
CAST(:by_mall AS jsonb), CAST(:sources AS jsonb), COALESCE(:partial, FALSE))
""")
params = {k: event.get(k) for k in _FIELDS}
by_mall = event.get("by_mall")
params["by_mall"] = json.dumps(by_mall) if by_mall is not None else None
for col in ("by_mall", "sources"): # JSONB 는 문자열로 넘겨 CAST 한다
v = event.get(col)
params[col] = json.dumps(v, ensure_ascii=False) if v is not None else None
s = await DB_SESSION_MNG.start_session(self.DB, DBWRType.DB_WRITE.value)
try:
await s.execute(sql, params)
@@ -55,7 +59,7 @@ class PriceHistory:
SELECT triggered_at, outcome, matched_count,
naver_lowest, naver_name, naver_url,
coupang_lowest, coupang_name, coupang_url,
final_lowest, final_source, by_mall
final_lowest, final_source, by_mall, sources, partial
FROM price_history
WHERE product_code = :pc
ORDER BY triggered_at DESC
@@ -76,7 +80,7 @@ class PriceHistory:
sql = text(f"""
SELECT * FROM (
SELECT DISTINCT ON (product_code)
product_code, triggered_at, outcome,
product_code, triggered_at, outcome, sources, partial,
naver_lowest, coupang_lowest, final_lowest, final_source,
COALESCE(naver_name, coupang_name) AS display_name,
count(*) OVER (PARTITION BY product_code) AS searches
+87
View File
@@ -0,0 +1,87 @@
# 2026-08-07 작업 기록 — IP 로테이션 검수 · 네이버 컨테이너 차단 규명 · 결과 상태 정의
다음 세션이 이어받을 수 있도록 **무엇이 왜 바뀌었고, 무엇이 남았는지**만 적는다.
상태 정의는 `result-states.md`, 운영 절차는 `operations.md` 가 소스다.
## 1. 무슨 일이 있었나
세 덩어리다. 앞의 둘은 "고장 났다"에서 출발했고, 셋째는 그 과정에서 드러난 설계 문제다.
**① IP 로테이션이 설계대로 안 돌고 있었다.** 검수해 보니 결함이 6개였고, 그중 하나는
`bot_detection.ip_request_no` 를 항상 `1` 로 만들어 **과거 진단 결론까지 오염**시켰다.
**② 컨테이너에서 네이버만 막혔다.** 원인은 컨테이너가 아니라 **UA 의 플랫폼 토큰**이었다.
네이버는 리눅스 데스크톱 Chrome 을 HTTP 405 로 거부한다.
**③ '못 봤다'를 '없다'고 말하고 있었다.** 차단당해 확인 못 한 몰이 화면에서 '없음(–)'과
구분되지 않았다. 상태를 정의하고 4단계로 화면까지 연결했다.
## 2. 지금 상태
| 항목 | 상태 |
|---|---|
| 네이버 | 컨테이너에서 정상(UA 보정). 검색당 40건 |
| 쿠팡 | **간헐적 차단** — 해외 IP(`gate`) 사용이 원인으로 추정(아래 4번) |
| IP 로테이션 | 예산·회전·소각이 모두 의도대로. 서킷브레이커가 풀 고갈 차단 |
| 결과 상태 | 몰별 7상태 → 운영자 화면은 그대로, 사용자 화면은 3가지로 접음 |
| 잡 | 한 소스가 막혀도 정상 종료(DEAD 아님) |
| 테스트 | lps 292 · negodata 107 passed |
| 배포 | 로컬 전체 재빌드·기동 완료. **운영은 마이그레이션 미적용**(아래 5번) |
## 3. 이번에 정한 것 (되돌리려면 근거부터 볼 것)
- **예산은 브라우저가 아니라 IP 에 묶는다.** 유휴 정리(120s)는 브라우저만 닫고 같은 IP 로
돌아오는데, 브라우저 기준으로 세면 카운터가 매번 초기화돼 **예산이 영영 발화하지 않는다**
(실측: 6회 검색이 전부 같은 포트·`ip_req#1`). 시계도 하나(`_session_started_at`)로 통일했다.
- **회전해도 소용없는 차단은 IP 를 태우지 않는다.** 서로 다른 IP 3개가 연속으로 **첫 요청부터**
막히면 IP 문제가 아니다(평판이면 몇 개는 통과하고, 과사용이면 뒤쪽에서 막힌다). 임계 없이
태우면 잡 16건에 100포트가 30분 쿨다운으로 묶인다. 성공 1회로 자동 해제된다.
- **임대 없이는 크롤하지 않는다.** 풀이 마르면 예전엔 계산식으로 포트를 골라 **남이 쥔 IP 를
같이 썼다**(실측 재현). 장부가 막으려던 바로 그 문제라, 못 잡으면 실패하는 게 맞다.
- **UA 는 플랫폼 토큰만 바꾸고 버전은 실제 값을 쓴다.** 통째로 하드코딩하면 컨테이너 Chrome 이
업데이트될 때 UA 와 엔진이 어긋나 그 불일치가 새 봇 신호가 된다. 쿠팡은 잘 통과하므로 안 건드린다.
- **상태는 하나로 정의·저장하고 표시 단계에서 접는다.** 저장을 단순화하면 운영자가 원인을 못 보고,
표시를 상세화하면 사용자가 못 읽는다. `partial` 을 컬럼으로 둔 것도 같은 이유 — 소비자가
'어떤 상태가 확인된 것인가'라는 판단 규칙까지 알면 상태 정의가 두 곳으로 흩어진다.
- **부분 실패의 `not_found` 는 네거티브 캐시에 넣지 않는다.** 못 본 몰에 있었을 수 있는데
'없음'으로 굳히면 TTL 동안 재검색이 막힌다(사용자가 '다시 검색'을 눌러도 캐시 히트).
## 4. 미해결 — 쿠팡 간헐적 차단
`사용권한이 제한된`(3.4KB)·`errors.edgesuite.net`(0.4KB) 마커로 막히는데 **IP 에 따라 갈린다**
(일부는 통과 → 서킷브레이커가 자동 해제). 즉 환경이 아니라 **IP 평판** 쪽이다.
유력한 원인: **쿠팡만 `gate`(국가 무지정 = 해외 IP)를 쓴다.** 네이버는 `kr_host`(한국 IP)로
바꾼 뒤 안정됐다. 같은 처방이 통할 가능성이 높다.
> 검증하려던 스크립트가 도구 시간 제한으로 중단됐다. 컨테이너에서 `gate` vs `kr` 통과율을
> IP 3개씩 비교하면 된다(네이버 UA 검증과 같은 방식).
⚠️ 맥 컨테이너는 amd64 를 **Rosetta 로 에뮬레이션**한다. 여기서 쿠팡이 막히는 건 실서버와
다를 수 있다 — 실서버에선 쿠팡이 60건 정상이었다. 판단은 실서버 로그로 한다.
## 5. 다음에 할 일 (우선순위)
1. **운영 DB 마이그레이션 적용** — 아직 안 됐다. 순서가 중요하다(아래 6번).
`6_lps_2026-08_dbeaver.sql`(lps_db) · `2026-08-07-iilp-source-state.sql`(negosium_db)
2. **쿠팡 KR 게이트웨이 검증** — 4번. 지금 최저가 커버리지의 최대 구멍이다.
3. **예산 튜닝** — F1 수정으로 `ip_request_no` 가 **처음으로 실제 사용량을 반영**한다.
`ip_req#1` 위주면 IP 평판, `2` 이상이면 예산 하향. **2026-08-06 이전 데이터는 쓰지 말 것.**
4. **AI 매칭 정확도 측정** — 세션 초반에 접근법만 논의하고 미착수. 정답 세트 20~30개로
"몇 % 맞나"를 재야 한다. 지금도 최저가 품질의 최대 병목이다.
5. lps-admin **잡 목록**에 몰별 상태 노출(상품 화면엔 이미 있음, 우선순위 낮음).
## 6. 작업 시 주의
- **마이그레이션 → 코드 순서를 지킬 것.** negodata 가 ORM 전체 엔티티를 조회하므로
(`lps_sync_crud.py:96`), 컬럼이 없는 DB 에 새 코드가 붙으면 **최저가 조회가 통째로 실패**한다
(재현 확인). 역순(마이그레이션 후 옛 코드)은 안전하다 — 옛 컨테이너로 실증했다.
- **워커를 켜 둔 채 pytest 하면 `test_job_queue` 3개가 깨진다.** 워커가 테스트 잡을 집어가서다.
코드 문제가 아니다 — `docker compose stop lps-worker` 후 돌리면 292 passed.
- **JS 로 브라우저 지문을 덮는 방법은 이 스택에서 통하지 않는다.** patchright 가
`add_init_script`(CDP 주입)를 무력화하고, MV3 확장도 값이 안 바뀐다. 다시 시도하기 전에
`services/search/fingerprint.py` docstring 을 볼 것.
- **로컬 dev 의 `negodata-front` 는 `node_modules` 가 named volume 이다.** 의존성이 늘면
이미지를 다시 빌드해도 반영되지 않는다 — 컨테이너 안에서 `npm install` 해야 한다(prod 은
`Dockerfile.prod` 라 해당 없음).
- 테스트가 실DB를 TRUNCATE 하는 문제는 그대로다(`price_history`·`job`·`ip_session`·`bot_detection`).
+2
View File
@@ -62,6 +62,8 @@
| `final_lowest` | 전체 최저가 (**그래프 Y축 핵심**) |
| `final_source` | 최종 최저가가 나온 소스(naver/coupang/gmarket/auction/st11) |
| `by_mall` | 몰별 최저가 스냅샷(JSONB, 열린 스키마) — `[{mall, source, price, shipping_fee, shipping_type, url}, …]`. G마켓·옥션·11번가 등이 늘어도 컬럼 추가 없이 담는다 |
| `sources` | **몰별 확인 상태**(JSONB) — `{"naver": {"state": "matched", "count": 40}, "coupang": {"state": "blocked", "error": "..."}}`. `by_mall` 은 가격이 있는 몰만 담으므로, 빠진 몰이 '거기엔 없더라'인지 '거기를 못 봤다'인지는 이 값에만 있다. state 값은 `SourceState`([정의](result-states.md)) |
| `partial` | 결과가 **완전한가**. `true`=못 본 몰이 있어 최종이 아니다. `sources` 에서 유도 가능하지만 컬럼으로 두어, 소비자가 상태 분류 규칙을 몰라도 되게 한다 |
| `job_id` / `created_at` | 검색 잡 연결 / 생성 시각 |
> 한쪽 소스에 그 상품이 없던 시점은 해당 컬럼이 `null`(그래프 선이 빈다 — 정상).
+233
View File
@@ -0,0 +1,233 @@
# 최저가 검색 결과 상태 정의
[← README로](../README.md)
`가격을 못 찾았다`는 한 문장 안에 **뜻이 정반대인 상황들**이 섞여 있다.
- 그 몰에 정말 그 상품이 없다 → 사실이다. 사용자는 받아들이면 된다.
- 그 몰이 우리를 막아서 못 봤다 → **사실이 아니다**. 더 싼 값이 있었을 수 있다.
지금 화면은 둘 다 `–` 로 똑같이 보여준다(2026-08-06 확인). 그래서 사용자는 "쿠팡엔 더 싼 게
없구나"로 읽지만 실제로는 **안 본 것**일 수 있다. 이 문서는 그 구분을 위해 상태를 정의한다.
상태는 두 층이다. **몰(소스) 단위**가 근본이고, **상품 단위**는 그것을 합친 결론이다.
그리고 보는 사람이 둘이다 — **운영자(lps-admin)는 원인까지** 알아야 하고,
**실 사용자(negodata)는 행동에 필요한 만큼만** 알면 된다. 상태는 하나로 정의·저장하고
표시 단계에서 각자에 맞게 접는다(3절).
---
## 1. 몰(소스) 단위 상태
한 상품을 한 몰에서 찾을 때 나올 수 있는 결과. 괄호 안은 **지금 코드가 그 상태를 아는지**.
| 상태 | 뜻 | 사용자에게 | 재시도 의미 |
|------|-----|-----------|------------|
| `matched` | 수집·매칭 성공, 가격 확보 | 가격 표시 | 불필요 |
| `no_match` | 수집은 됐으나 **같은 상품이 없음**(액세서리·다른 규격만 나옴) | "해당 상품 없음" | 검색어를 고치면 달라질 수 있음 |
| `empty` | 그 몰의 **검색 결과 자체가 0건** | "해당 상품 없음" | 검색어 의존 |
| `blocked` | 안티봇 차단 — **못 봤다** | "확인 못함" | ✅ 유효(IP 회전으로 회복) |
| `env_blocked` | 회전해도 안 되는 차단(환경·게이트웨이 설정) | "확인 못함" | ❌ 사람이 고쳐야 함 |
| `unavailable` | 가용 IP 없음·프록시 사망 등 일시적 실패 | "확인 못함" | ✅ 잠시 후 유효 |
| `skipped` | 그 소스를 아예 안 씀(오픈마켓 폴백 OFF 등) | 열 자체를 안 보임 | 해당 없음 |
**핵심 경계는 `no_match`/`empty`(= 사실) 와 `blocked`/`env_blocked`/`unavailable`(= 미확인) 사이다.**
앞의 둘은 "없다"고 말해도 되고, 뒤의 셋은 말하면 안 된다.
### 지금 코드가 아는 것 / 잃는 것
어댑터는 이미 이 구분을 **알고 있다**. `AdapterError` 에 `blocked`·`fatal` 플래그가 있고,
0건일 때 `detect_block` 으로 '차단인가 정상 빈결과인가'를 판정한다(browser_base.py).
```
0건 응답 → detect_block(html, ...) → marker
marker 있음 → blocked=True (fatal 마커면 fatal=True)
marker 없음 → blocked=False ← '정상 빈결과' = empty
```
그런데 **핸들러가 그 플래그를 버린다**:
```python
# worker/handlers.py — _search_round
per_source[src] = {"error": f"{type(res).__name__}: {res}"} # ← blocked/fatal 유실, 문자열만 남음
```
⚠️ 그리고 **0건도 예외로 온다**(`return` 은 상품이 1건 이상일 때만). 즉 `empty` 와 `blocked` 가
둘 다 `AdapterError` 로 도착하는데, 구분 플래그를 버리므로 핸들러 이후로는 갈라낼 수 없다.
| 상태 | 어댑터가 아는가 | 핸들러가 아는가 | price_history 에 남는가 |
|------|----------------|----------------|----------------------|
| `matched` | ✅ | ✅ | ✅ `by_mall` 에 등장 |
| `no_match` | — | ✅ (수집>0, 매칭 0) | ❌ 유도만 가능, 기록 없음 |
| `empty` | ✅ `blocked=False` | ❌ 유실 | ❌ |
| `blocked` | ✅ `blocked=True` | ❌ 유실 | ❌ |
| `env_blocked` | ✅ `fatal=True` | ❌ 유실 | ❌ |
| `unavailable` | ✅ 별도 메시지 | ❌ 유실 | ❌ |
→ **고칠 지점은 한 곳이다**: `_search_round` 가 플래그를 구조화해 넘기고, 그게 `price_history`
까지 가면 된다. 새로 알아내야 할 정보는 없다 — 이미 아는 걸 흘리고 있을 뿐이다.
---
## 2. 상품 단위 상태
몰별 상태를 합친 결론. `price_history.outcome` 이 이 값이다.
| 상태 | 조건 | 뜻 | 현재 지원 |
|------|------|-----|----------|
| `found` | 매칭 1건 이상 | 최저가 확정 | ✅ |
| `not_found` | 모든 소스가 사실 응답(`no_match`/`empty`)이고 매칭 0 | **확정적 없음** | ✅ |
| `error` | 모든 소스가 미확인(`blocked` 계열) | **아무것도 확인 못함** | ✅ (2026-08-06 추가) |
| `partial` | 일부 소스만 미확인 | 아래 참고 | ⚠️ 부분 지원 |
### `partial` 이 중요한 이유
`partial` 은 독립된 상태가 아니라 **`found`/`not_found` 에 붙는 꼬리표**다. 조합이 넷인데
사용자에게 주는 의미가 전혀 다르다.
| 조합 | 뜻 | 사용자에게 할 말 |
|------|-----|----------------|
| `found` | 전 소스 확인, 최저가 확정 | "최저가 N원" |
| `found` + `partial` | 찾긴 했지만 **못 본 몰이 있다** | "최저가 N원 (쿠팡은 확인 못함)" |
| `not_found` | 전 소스 확인, 확정적 없음 | "찾지 못했습니다" |
| `not_found` + `partial` | **결론이 아니다** — 못 본 몰에 있었을 수 있다 | "확인하지 못했습니다" |
특히 마지막이 위험하다. 이걸 `not_found` 로 뭉뚱그리면:
- 사용자는 "없구나"로 오해하고
- 네거티브 캐시에 들어가면 TTL 동안 재검색까지 막힌다
→ 그래서 **부분 실패 상태의 `not_found` 는 네거티브 캐시에 넣지 않는다**(2026-08-06 반영).
`partial` 플래그 자체는 `job.result` 에 있지만 `price_history` 에는 없어 화면까지 가지 못한다.
---
## 3. 화면 표기 — 보는 사람이 다르면 다르게 접는다
**상태는 하나만 정의하고 상세하게 저장한다. 접는 건 표시 단계에서 한다.**
저장을 단순화하면 관리자가 원인을 못 보고, 표시를 상세화하면 사용자가 못 읽는다.
두 화면 모두 `price_history` 를 읽으므로(lps-admin: 잡·이력 조회 / negodata: 최저가 모달),
데이터는 공유하고 **투영만 달리한다**.
### 3-1. lps-admin (운영자) — 상세하게
목적이 **진단**이다. "왜 그랬나"에 답할 수 있어야 하므로 7상태를 그대로 보여주고 근거를 붙인다.
| 표시 | 내용 |
|------|------|
| 몰별 상태 | `matched` / `no_match` / `empty` / `blocked` / `env_blocked` / `unavailable` 그대로 |
| 근거 | 차단 마커(`wtm_captcha`·`사용권한이 제한된`…), `ip_request_no`, 포트 |
| 조치 힌트 | `env_blocked` → "설정·환경 문제, 회전 무효" / `blocked` → "IP 평판, 자동 회복" |
`env_blocked` 와 `blocked` 를 반드시 갈라야 한다 — **사람이 개입해야 하는가**가 갈리기 때문이다.
이 구분이 없으면 운영자가 자동 회복될 일에 매달리거나, 손봐야 할 설정을 방치한다.
### 3-2. negodata (실 사용자) — 접어서
목적이 **행동**이다. 사용자가 할 수 있는 건 '이 가격을 쓴다 / 다시 시도한다 / 넘어간다' 셋뿐이라,
그 이상 나눠 보여줄 이유가 없다. 원인이 달라도 **사용자의 다음 행동이 같으면 같은 표기**로 접는다.
| 내부 상태 | 사용자 표기 | 접는 이유 |
|-----------|------------|----------|
| `matched` | 가격 | |
| `no_match` · `empty` | `–` | 둘 다 "이 몰엔 없다"가 결론. 원인(불일치냐 0건이냐)을 알아도 사용자가 할 일이 안 바뀐다 |
| `blocked` · `env_blocked` · `unavailable` | **확인 못함** | 원인이 달라도 사용자 행동은 '나중에 다시' 하나뿐. 차단 종류를 노출하면 불안만 준다 |
| `skipped` | 열 숨김 | 안 쓴 소스를 '없음'처럼 보이면 안 된다 |
결과 열도 같은 원칙으로 접는다.
| 사용자 표기 | 조건 |
|------------|------|
| 탐색 성공 | `found` 이고 기존보다 쌈 |
| 변동 없음 | `found`(더 싸진 않음) 또는 `not_found` |
| **일부 확인 못함** | `partial` — 결과가 확정이 아님을 알린다 |
| 탐색 실패 | `error` — 전부 미확인 |
| 탐색 중 | 아직 결과 행이 없음 |
> **'일부 확인 못함'은 접지 않는다.** 다른 항목과 달리 이건 사용자의 행동을 바꾼다 —
> "이 가격이 최종인가"의 답이 달라지고, 다시 시도할 이유가 생긴다. 사용자에게 필요한 건
> *어느 몰이 왜 막혔는지*가 아니라 **결과가 완전하지 않다는 사실 하나**다.
---
## 4. 현재 상태와 남은 일
**된 것**
- `error`(전부 미확인)를 `not_found` 와 분리 — 화면이 "탐색 실패"로 구분해 보여준다
- 부분 실패 시 네거티브 캐시 오염 방지
- 한 소스가 막혀도 살아있는 소스로 잡을 정상 종료
### 진행 상황
**1단계 — 몰별 상태 보존 ✅ 완료** (`feat/source-state`)
- `common/enums.py` 에 `SourceState`(7상태) 추가. `.confirmed` 로 '봤다/못 봤다' 경계를 한곳에 둔다.
- `AdapterError.state` — 어댑터가 이미 알던 구분을 실어 보낸다. `state` 를 안 주면
`blocked/fatal` 에서 유도하고, **모르면 `UNAVAILABLE`**(= 못 봤다)로 둔다.
`EMPTY` 를 기본값으로 하면 확인도 안 한 몰을 '없음'으로 단정하게 되기 때문이다.
- `browser_base` 의 raise 지점 5곳에 상태를 실었다. 갈림은 0건 종착 지점 하나다:
`blocked=False` → `EMPTY`(정말 없다) / `blocked=True` → `BLOCKED`(못 봤다).
- `_search_round` 가 문자열 대신 `{"state": ..., "count"|"error": ...}` 를 남긴다.
`EMPTY` 는 '정상 응답'으로 세므로, 쿠팡에 정말 없을 때 잡이 재시도로 낭비되지 않는다.
- `_finalize_states` — 수집만 된 소스를 AI 판정 뒤 `MATCHED`/`NO_MATCH` 로 확정한다.
검증(9조합 실측): `empty` → `partial=False`(확정) / `blocked`·`env_blocked`·`unavailable`
→ `partial=True`(미확정). 테스트 12건 추가.
**2단계 — 저장할 자리 ✅ 완료** (`feat/source-state`)
- `price_history.sources`(JSONB) — 몰별 상태를 그대로 담는다. 열린 스키마라 몰이 늘거나
상태에 근거를 덧붙여도 마이그레이션이 필요 없다.
- `price_history.partial`(bool) — 결과가 완전한가. `sources` 에서 유도할 수 있지만 굳이 컬럼으로
둔다: 소비자가 '어떤 상태가 확인된 것인가'라는 **판단 규칙까지 알아야 하면 상태 정의가 두 곳으로
흩어진다**. 판단은 LPS 가 끝내고 소비자는 사실 하나만 읽는다.
- 부분 인덱스 `ix_price_history_partial` — '확인 못한 결과'만 뽑는 운영 점검용(작게 유지된다).
- 마이그레이션: `postgres-init/dbeaver/6_lps_2026-08_dbeaver.sql` (2026-08 추가분 통합, **운영 적용 필요**)
검증(실 DB): 쿠팡 차단과 쿠팡 0건은 `by_mall` 이 둘 다 `['naver']` 로 같지만
`partial`(true/false)과 `sources.coupang.state`(blocked/empty)가 두 경우를 갈라낸다. 테스트 3건 추가.
**3단계 — lps-admin 상세 표시 ✅ 완료** (`feat/source-state`)
운영자 목적은 **진단**이라 상태를 접지 않는다 — `blocked`(자동 회복)와 `env_blocked`(사람이
고쳐야 함)를 뭉뚱그리면 회복될 일에 매달리거나 손봐야 할 설정을 방치한다.
- API: `/v1/lps/products` 와 `/v1/lps/products/{code}/history` 둘 다 `sources`·`partial` 을 싣는다.
**이력은 시점마다** 실린다 — 최신 상태를 과거 시점 옆에 붙이면 오해를 부르기 때문이다.
- `lps-admin/src/lib/sourceState.ts`: 상태별 라벨·색·설명·`confirmed` 를 한곳에 둔다.
미지의 상태가 와도 화면이 깨지지 않는다(값 그대로 표시하고 '모름'으로 취급).
- 상품 목록: 못 본 몰이 있으면 `일부 확인 못함` 배지(툴팁에 어느 몰인지).
- 몰별 비교 카드 위: 몰별 상태 줄 + 수집 건수 + 실패 사유 원문(툴팁). 가격표에 없는 몰이
**왜** 없는지를 여기서 답한다.
검증: ASGI 직접 호출로 두 엔드포인트 모두 `sources`·`partial` 확인(한글 사유 포함).
`tsc` 오류 없음. 테스트 3건 추가(목록 노출 / 시점별 상태 / 옛 행 호환).
**4단계 — negodata 사용자 화면 ✅ 완료** (`feat/source-state`)
3-2절대로 **셋으로 접었다**. 사용자가 할 수 있는 건 '쓴다/다시 시도/넘어간다' 뿐이라, 원인이
달라도 다음 행동이 같으면 같은 표기다.
| 몰 칸 | 조건 |
|------|------|
| 가격 | `matched` |
| `–` | `no_match` · `empty` — 확인했고 없었다 |
| **확인 못함** | `blocked` · `env_blocked` · `unavailable` — 못 봤다 |
체인 전체를 이었다: `price_history.sources/partial` → negodata 읽기 계약 → 동기화 →
`item_internet_lowest_prices` → API(`LowestPriceEntry`) → 화면.
마이그레이션: `postgres-init/alters/2026-08-07-iilp-source-state.sql` (**운영 적용 필요**)
E2E 검증(실 DB, 두 시나리오): `by_mall` 은 둘 다 `naver` 뿐인데 쿠팡 칸이
`확인 못함`(차단) / `–`(0건)으로 갈린다. `tsc` 오류 없음, negodata 97 · lps 292 passed.
> 폴더 관례상 negodata 는 인수인계 대상이나, 사용자 요청으로 이번 건도 예외 적용.
---
**4단계 모두 완료.** 남은 개선 여지(선택):
- `no_match`(같은 상품 아님)와 `empty`(검색 0건)를 사용자 화면에서 굳이 나눌 필요는 없다고 봤다 —
나중에 "왜 없지?"라는 문의가 잦아지면 재검토.
- 잡 목록(lps-admin Jobs)에는 아직 몰별 상태를 안 붙였다. 상품 화면에서 보이므로 우선순위는 낮다.
> 이 문서는 **정의**다. 구현 전에 용어를 맞추기 위한 것이고, 실제 반영 여부는 위 4절이 소스다.
+4
View File
@@ -45,6 +45,10 @@ class ProductItem(BaseModel):
final_lowest: Optional[int] = None
final_source: Optional[str] = None
searches: int = Field(0, description="누적 검색(이력) 수")
# 운영 화면은 **원인까지** 봐야 한다 — '그 몰에 없었다'와 '그 몰을 못 봤다'는 조치가 다르다
# (전자는 검색어 문제, 후자는 IP·환경 문제). 사용자 화면은 이걸 접어서 보여준다.
sources: Optional[dict] = Field(None, description="몰별 확인 상태 — {몰: {state, count|error}}. state=SourceState")
partial: bool = Field(False, description="못 본 몰이 있어 결과가 최종이 아님")
class Res_ProductList(Res_WebPacketProtocol):
+3
View File
@@ -61,6 +61,9 @@ class PricePoint(BaseModel):
coupang_name: Optional[str] = None
coupang_url: Optional[str] = None
by_mall: Optional[list[dict]] = Field(None, description="몰별 최저가 스냅샷(G마켓·옥션·11번가 등 포함)")
# by_mall 은 **가격이 있는 몰만** 담는다 — 빠진 몰이 '없었다'인지 '못 봤다'인지는 아래에만 있다.
sources: Optional[dict] = Field(None, description="몰별 확인 상태 — {몰: {state, count|error}}")
partial: bool = Field(False, description="못 본 몰이 있어 이 시점 결과가 최종이 아님")
class Res_PriceHistory(Res_WebPacketProtocol):
+1
View File
@@ -87,6 +87,7 @@ class AdminService:
naver_lowest=r.get("naver_lowest"), coupang_lowest=r.get("coupang_lowest"),
final_lowest=r.get("final_lowest"), final_source=r.get("final_source"),
searches=int(r.get("searches") or 0),
sources=r.get("sources"), partial=bool(r.get("partial")),
) for r in await self.history.list_products(q, limit)]
return res
+1
View File
@@ -95,6 +95,7 @@ class LpsService:
naver_name=r["naver_name"], naver_url=r["naver_url"],
coupang_name=r["coupang_name"], coupang_url=r["coupang_url"],
by_mall=r.get("by_mall"),
sources=r.get("sources"), partial=bool(r.get("partial")),
)
for r in rows
]
+16 -5
View File
@@ -20,6 +20,7 @@ from abc import abstractmethod
from patchright.async_api import async_playwright
from common.logger import LOG
from common.enums import SourceState
from config.server_configs import decodo_config, worker_config
from services.search.contract import SearchAdapter, NormalizedProduct, AdapterError, AdapterHealth
from services.search.rate_limiter import RateLimiter
@@ -253,7 +254,7 @@ class BrowserSearchAdapter(SearchAdapter):
self._note_result(False)
raise AdapterError(
f"{self.source} 가용 프록시 IP 없음(전부 임대/휴식/쿨다운) — 잠시 후 재시도",
source=self.source)
source=self.source, state=SourceState.UNAVAILABLE)
kwargs["proxy"] = self._proxy.playwright_proxy()
await self._begin_ip_session(self._proxy.current_port)
else:
@@ -409,7 +410,9 @@ class BrowserSearchAdapter(SearchAdapter):
self._rotate_ip(f"프록시 전송오류({type(ex).__name__}) 재시도 {self.max_proxy_retries - proxy_retries}/{self.max_proxy_retries}", kind="proxy_error")
continue
self._note_result(False)
raise AdapterError(f"{self.source} 검색 실패: {ex}", source=self.source) from ex
# 페이지를 못 받았다 = 그 몰을 **못 봤다**. '없음'과 섞이면 안 된다.
raise AdapterError(f"{self.source} 검색 실패: {ex}", source=self.source,
state=SourceState.UNAVAILABLE) from ex
# 실제 프록시 전송 바이트(CDP encodedDataLength) — 미지원 시 DOM 크기 폴백
self.last_bytes = self._net_bytes if self._cdp is not None else len(html.encode("utf-8"))
@@ -436,7 +439,8 @@ class BrowserSearchAdapter(SearchAdapter):
f"[{self.source}] 구조적 차단 '{marker}' — IP 회전으로 회복 불가. "
f"게이트웨이/국가 설정을 확인하세요([DecodoConfig].kr_host 등)")
raise AdapterError(f"{self.source} 구조적 차단 ({marker}) — 설정 확인 필요",
source=self.source, blocked=True, fatal=True)
source=self.source, blocked=True, fatal=True,
state=SourceState.ENV_BLOCKED)
# 확신도에 따라 대응을 가른다.
# 알려진 마커 사이트가 대놓고 막았다 → 태울 근거가 있다
# short_html 폴백 '0건인데 페이지가 짧다'는 정황일 뿐이다. 진짜 '검색결과
@@ -459,7 +463,8 @@ class BrowserSearchAdapter(SearchAdapter):
raise AdapterError(
f"{self.source} 환경 차단 (IP {len(self._fresh_ip_blocks)}개가 첫 요청부터 차단, "
f"최근 마커={marker}) — IP 회전으로 회복 불가",
source=self.source, blocked=True, fatal=True)
source=self.source, blocked=True, fatal=True,
state=SourceState.ENV_BLOCKED)
if known and self.uses_proxy:
self._proxy.mark_burned(self._current_port) # 불탄 포트 — 쿨다운 격리(로테이션이 건너뜀)
@@ -471,7 +476,13 @@ class BrowserSearchAdapter(SearchAdapter):
if blocked: # 재시도 소진/비활성 — 불탄 포트로 다음 검색을 하지 않도록 회전만 예약하고 포기
self._rotate_ip("봇 감지 — 다음 검색은 새 IP", kind="block")
self._note_result(False)
raise AdapterError(f"{self.source} 결과 없음/차단 (query={query!r}, blocked={blocked})", source=self.source, blocked=blocked)
# 여기가 '없음'과 '못 봄'이 갈리는 유일한 지점이다.
# blocked=False → 페이지는 정상인데 상품이 0건 = 그 몰에 **정말 없다**(EMPTY)
# blocked=True → 차단 페이지를 받은 것 = **못 봤다**(BLOCKED)
# 이 구분을 여기서 안 실어 보내면 위쪽에서는 영영 알 수 없다.
raise AdapterError(f"{self.source} 결과 없음/차단 (query={query!r}, blocked={blocked})",
source=self.source, blocked=blocked,
state=SourceState.BLOCKED if blocked else SourceState.EMPTY)
async def _report_detection(self, query: str, marker: str, html_len: int):
# 경과는 **IP 세션** 기준 — 'ip_req#N 을 몇 초 만에 쐈나'가 차단 진단의 축이다.
+15 -1
View File
@@ -12,6 +12,8 @@ from typing import Optional
from pydantic import BaseModel, Field
from common.enums import SourceState
class NormalizedProduct(BaseModel):
"""소스 무관 정규화 상품 스키마. 어댑터의 유일한 출력 계약."""
@@ -55,13 +57,25 @@ class AdapterError(Exception):
fatal=True 는 **재시도해도 절대 안 되는 차단**이다 — IP 를 바꿔도 같은 결과가 나오는
구조적 원인(예: 네이버 msearch 에 해외 IP 로 접근 = 게이트웨이 설정이 틀림).
호출부는 회전·재시도를 멈추고 설정을 고쳐야 한다.
⚠️ `state` 는 **'그 몰을 봤는가'** 를 담는다. blocked/fatal 은 '어떻게 대응할까'(회전·재시도)를
위한 값이고, state 는 '사용자에게 뭐라고 말할까'를 위한 값이라 쓰임이 다르다.
특히 blocked=False 하나에 두 가지가 섞여 있어 state 없이는 갈라낼 수 없다:
결과 0건(EMPTY) 그 몰을 봤고 정말 없었다 → "없음"이라 말해도 된다
전송 실패(UNAVAILABLE) 그 몰을 못 봤다 → "없음"이라 말하면 거짓
"""
def __init__(self, message: str, *, source: str, blocked: bool = False, fatal: bool = False):
def __init__(self, message: str, *, source: str, blocked: bool = False, fatal: bool = False,
state: SourceState | None = None):
super().__init__(message)
self.source = source
self.blocked = blocked
self.fatal = fatal
# state 를 안 준 옛 호출부도 맞게 동작하도록 blocked/fatal 에서 유도한다.
# (모르면 UNAVAILABLE — '못 봤다' 쪽이 안전한 기본값이다. EMPTY 로 잘못 넘기면
# 확인도 안 한 몰을 '없음'으로 단정하게 된다)
self.state = state or (SourceState.ENV_BLOCKED if fatal else
SourceState.BLOCKED if blocked else SourceState.UNAVAILABLE)
class SearchAdapter(ABC):
+46
View File
@@ -95,6 +95,52 @@ async def test_products_list_latest_snapshot(client, clean_all):
assert len(r.json()["items"]) == 1
# ---- 몰별 확인 상태 (2026-08-07, 3단계) -------------------------------------
# 운영 화면은 '왜 그 몰 값이 없나'에 답할 수 있어야 한다 — by_mall 에 없는 몰이
# '거기엔 없더라'인지 '거기를 못 봤다'인지는 sources 에만 있다.
async def test_products_list_exposes_source_states(client, clean_all):
async with clean_all.begin() as conn:
await conn.execute(text("""
INSERT INTO price_history (product_code, outcome, final_lowest, partial, sources, triggered_at)
VALUES ('S1', 'found', 9000, true,
'{"naver": {"state": "matched", "count": 40},
"coupang": {"state": "env_blocked", "error": "사용권한이 제한된"}}'::jsonb,
now())
"""))
item = (await client.get("/v1/lps/products")).json()["items"][0]
assert item["partial"] is True
assert item["sources"]["coupang"]["state"] == "env_blocked"
assert "사용권한이 제한된" in item["sources"]["coupang"]["error"] # 원인 원문이 운영자에게 간다
async def test_history_points_carry_state_per_point(client, clean_all):
"""상태는 시점마다 다르다 — 최신 상태를 과거 시점 옆에 붙이면 오해를 부른다."""
async with clean_all.begin() as conn:
await conn.execute(text("""
INSERT INTO price_history (product_code, outcome, final_lowest, partial, sources, triggered_at)
VALUES ('S2', 'found', 9000, true,
'{"coupang": {"state": "blocked"}}'::jsonb, now() - interval '1 hour'),
('S2', 'found', 8500, false,
'{"coupang": {"state": "matched", "count": 60}}'::jsonb, now())
"""))
pts = (await client.get("/v1/lps/products/S2/history")).json()["points"]
assert [p["partial"] for p in pts] == [True, False]
assert pts[0]["sources"]["coupang"]["state"] == "blocked"
assert pts[1]["sources"]["coupang"]["state"] == "matched"
async def test_old_rows_without_state_still_work(client, clean_all):
"""이 컬럼 추가 이전 이력도 그대로 읽혀야 한다(마이그레이션 전 데이터)."""
async with clean_all.begin() as conn:
await conn.execute(text("""
INSERT INTO price_history (product_code, outcome, final_lowest, triggered_at)
VALUES ('S3', 'found', 7000, now())
"""))
item = (await client.get("/v1/lps/products")).json()["items"][0]
assert item["partial"] is False and item.get("sources") is None
# ---- 통계 3종 ---------------------------------------------------------------
async def test_ip_session_stats(client, clean_all):
+39
View File
@@ -113,3 +113,42 @@ async def test_snapshot_carries_trust_of_the_lowest_offer():
e = rec.events[0]
assert e["final_lowest"] == 900 and e["final_source"] == "naver"
assert e["final_rating"] is None and e["final_review_count"] is None # 미검증 오퍼임이 드러난다
# ── 몰별 확인 상태 (2026-08-07, 2단계) ──────────────────────────────────
# by_mall 은 '가격이 있는 몰'만 담는다. 그래서 어떤 몰이 빠졌을 때 '거기엔 없더라'인지
# '거기를 못 봤다'인지 구분되지 않았다 — sources/partial 이 그 자리를 메운다.
async def test_records_source_states_and_partial(ph, db_engine):
await ph.record({
"product_code": "SRC1", "outcome": "found", "final_lowest": 9000, "partial": True,
"sources": {"naver": {"state": "matched", "count": 40},
"coupang": {"state": "blocked", "error": "AdapterError: 차단"}},
})
async with db_engine.begin() as conn:
row = (await conn.execute(text(
"SELECT partial, sources FROM price_history WHERE product_code='SRC1'"))).first()
assert row.partial is True
assert row.sources["coupang"]["state"] == "blocked"
assert row.sources["naver"]["count"] == 40
async def test_partial_defaults_to_false_when_absent(ph, db_engine):
"""옛 호출부(값을 안 주는 경로)도 깨지지 않아야 한다 — 기본은 '완전한 결과'."""
await ph.record({"product_code": "SRC2", "outcome": "not_found"})
async with db_engine.begin() as conn:
row = (await conn.execute(text(
"SELECT partial, sources FROM price_history WHERE product_code='SRC2'"))).first()
assert row.partial is False and row.sources is None
async def test_source_state_survives_korean_text(ph, db_engine):
"""error 메시지에 한글이 섞여도 JSONB 가 깨지지 않아야 한다(ensure_ascii=False)."""
await ph.record({
"product_code": "SRC3", "outcome": "found", "partial": True,
"sources": {"coupang": {"state": "env_blocked", "error": "사용권한이 제한된 페이지"}},
})
async with db_engine.begin() as conn:
row = (await conn.execute(text(
"SELECT sources FROM price_history WHERE product_code='SRC3'"))).first()
assert "사용권한이 제한된" in row.sources["coupang"]["error"]
+54 -3
View File
@@ -69,6 +69,15 @@ class FakeNegCache:
self.puts.append(key)
class FakeHistory:
"""price_history 기록 관찰용 — '행이 남는가'가 프론트의 대기/표시를 가른다."""
def __init__(self):
self.events = []
async def record(self, event):
self.events.append(event)
def _np(source, price, mall=None):
return NormalizedProduct(source=source, name=f"{source}-{price}", price=price, mall_name=mall)
@@ -130,10 +139,52 @@ async def test_negative_cache_short_circuits():
assert adapters["naver"].calls == [] # 재검색 안 함
async def test_technical_failure_with_zero_match_raises():
adapters = {"coupang": FakeAdapter("coupang", fail=True), "naver": FakeAdapter("naver", by_query={})}
# ── 부분 결과: 한 소스가 막혀도 살아있는 소스로 답한다 (2026-08-06) ──────
# 예전엔 한 소스라도 실패하면 무조건 raise → 재시도 → DEAD 였다. 그런데 DEAD 는 price_history 에
# 행을 남기지 않아, 이를 폴링하는 negodata 최저가 모달이 결과를 영영 못 받고 '탐색 중'에서 멈췄다
# (실측: 쿠팡이 막힌 동안 네이버가 40건씩 가져왔는데도 잡이 전부 DEAD).
async def test_all_sources_failing_still_retries():
"""전부 죽었으면 '없음'이라 단정할 수 없다 — 이때는 기존대로 재시도한다."""
adapters = {"coupang": FakeAdapter("coupang", fail=True), "naver": FakeAdapter("naver", fail=True)}
with pytest.raises(RuntimeError):
await build_search_handler(adapters)(_job()) # 0매칭 + 차단 → 기술 재시도
await build_search_handler(adapters)(_job())
async def test_partial_failure_completes_with_the_surviving_source():
"""쿠팡이 막혀도 네이버가 찾았으면 정상 종료해야 한다(사용자가 결과를 받는 게 우선)."""
adapters = {"coupang": FakeAdapter("coupang", fail=True),
"naver": FakeAdapter("naver", products=[_np("naver", 9000)])}
r = await build_search_handler(adapters, judge=FakeJudge(lambda c: True))(_job())
assert r["outcome"] == "found" and r["lowest"]["price"] == 9000
assert r["partial"] is True and r["sources_failed"] == ["coupang"] and r["sources_ok"] == ["naver"]
async def test_partial_zero_match_ends_as_not_found_not_dead():
"""살아있는 소스가 0매칭이면 not_found 로 **정상 종료**한다 — 잡을 죽이면 화면이 멈춘다."""
adapters = {"coupang": FakeAdapter("coupang", fail=True), "naver": FakeAdapter("naver", by_query={})}
r = await build_search_handler(adapters)(_job())
assert r["outcome"] == "not_found" and r["partial"] is True
async def test_partial_not_found_does_not_poison_the_negative_cache():
"""막힌 소스엔 있었을 수 있다 — '없음'으로 굳히면 TTL 동안 재검색이 막힌다."""
adapters = {"coupang": FakeAdapter("coupang", fail=True), "naver": FakeAdapter("naver", by_query={})}
neg = FakeNegCache()
r = await build_search_handler(adapters, neg_cache=neg)(_job())
assert r["outcome"] == "not_found"
assert neg.puts == [], "부분 실패 상태의 not_found 는 캐시하지 않는다"
async def test_all_sources_failed_on_last_attempt_records_error_instead_of_dying():
"""재시도가 소진되면 DEAD 대신 error 로 기록한다 — 이력이 남아야 화면이 '실패'를 보여준다."""
adapters = {"coupang": FakeAdapter("coupang", fail=True), "naver": FakeAdapter("naver", fail=True)}
hist = FakeHistory()
job = _job()
job.update(attempts=3, max_attempts=3) # 마지막 시도
r = await build_search_handler(adapters, history=hist)(job)
assert r["outcome"] == "error" and r["sources_ok"] == []
assert [e["outcome"] for e in hist.events] == ["error"], "이력이 없으면 프론트가 계속 대기한다"
# ── 오픈마켓 폴백 크롤 (네이버 미커버 몰만) ──────────────────────────
+107
View File
@@ -0,0 +1,107 @@
"""몰(소스)별 상태 테스트 — '그 몰에 없었다'와 '그 몰을 못 봤다'를 가르는 계약.
정의는 docs/result-states.md 가 소스다. 여기서 지키는 것은 하나다:
**확인한 것(matched/no_match/empty)과 못 본 것(blocked/env_blocked/unavailable)이 섞이지 않는다.**
섞이면 차단당해 못 본 몰이 화면에서 '그 몰엔 없음'으로 둔갑한다(실제로 그랬다).
"""
import pytest
from common.enums import SourceState
from services.search.contract import AdapterError, NormalizedProduct, SearchAdapter
from worker.handlers import _finalize_states, build_search_handler
# ── 상태 자체의 계약 ────────────────────────────────────────────────────
def test_confirmed_separates_seen_from_unseen():
"""이 경계가 무너지면 나머지 로직이 전부 틀어진다."""
assert [s for s in SourceState if s.confirmed] == [
SourceState.MATCHED, SourceState.NO_MATCH, SourceState.EMPTY]
for s in (SourceState.BLOCKED, SourceState.ENV_BLOCKED, SourceState.UNAVAILABLE, SourceState.SKIPPED):
assert not s.confirmed, s
# ── AdapterError 가 상태를 싣는가 ───────────────────────────────────────
@pytest.mark.parametrize("kw,expected", [
(dict(), SourceState.UNAVAILABLE), # 아무것도 모르면 '못 봤다'가 안전
(dict(blocked=True), SourceState.BLOCKED),
(dict(blocked=True, fatal=True), SourceState.ENV_BLOCKED),
(dict(state=SourceState.EMPTY), SourceState.EMPTY),
])
def test_error_state_defaults(kw, expected):
"""state 를 안 준 옛 호출부도 맞게 동작해야 한다 — 특히 기본값이 EMPTY 면 안 된다
(확인도 안 한 몰을 '없음'으로 단정하게 된다)."""
assert AdapterError("x", source="s", **kw).state is expected
# ── 수집 뒤 매칭 결과로 확정 ────────────────────────────────────────────
def test_collected_but_unmatched_becomes_no_match():
per_source = {"naver": {"state": "matched"}, "coupang": {"state": "matched"}}
matched = [NormalizedProduct(source="naver", name="x", price=1)]
_finalize_states(per_source, matched)
assert per_source["naver"]["state"] == "matched"
assert per_source["coupang"]["state"] == "no_match" # 가져왔지만 같은 상품이 아니었다
def test_finalize_never_overwrites_a_failure_state():
"""실패 상태는 이미 확정이다 — 매칭 결과로 덮으면 '못 봤다'가 사라진다."""
per_source = {"coupang": {"state": "blocked"}, "naver": {"state": "empty"}}
_finalize_states(per_source, [])
assert per_source["coupang"]["state"] == "blocked"
assert per_source["naver"]["state"] == "empty"
# ── 핸들러 통합: 상태가 결과까지 실려 나가는가 ──────────────────────────
class _A(SearchAdapter):
def __init__(self, source, mode): self.source, self.mode = source, mode
async def search(self, q, limit=40):
if self.mode == "hit":
return [NormalizedProduct(source=self.source, name="생수 2L", price=9000)]
if self.mode == "empty":
raise AdapterError("결과 없음", source=self.source, state=SourceState.EMPTY)
if self.mode == "blocked":
raise AdapterError("차단", source=self.source, blocked=True, state=SourceState.BLOCKED)
raise RuntimeError("우리 코드 버그")
def _job():
return {"job_type": 1, "job_id": "J", "attempts": 1, "max_attempts": 3,
"payload": {"product_code": "P", "product_name": "생수"}}
async def _run(modes):
return await build_search_handler({s: _A(s, m) for s, m in modes.items()})(_job())
async def test_empty_is_a_confirmed_answer_not_a_gap():
"""봤는데 없었으면 결과는 **확정**이다 — partial 로 흐리면 안 된다."""
r = await _run({"naver": "hit", "coupang": "empty"})
assert r["sources"]["coupang"]["state"] == "empty"
assert r["partial"] is False and r["sources_failed"] == []
async def test_blocked_marks_the_result_incomplete():
"""못 본 몰이 있으면 그 결과는 최종이 아니다."""
r = await _run({"naver": "hit", "coupang": "blocked"})
assert r["sources"]["coupang"]["state"] == "blocked"
assert r["partial"] is True and r["sources_failed"] == ["coupang"]
async def test_unknown_exception_counts_as_unseen():
"""우리 코드 버그로 못 본 것도 '없음'이라 말하면 안 된다."""
r = await _run({"naver": "hit", "coupang": "boom"})
assert r["sources"]["coupang"]["state"] == "unavailable"
assert r["partial"] is True
async def test_all_empty_is_a_definitive_not_found():
"""전부 확인했고 없었다 → 확정적 not_found(네거티브 캐시에 넣어도 되는 상태)."""
r = await _run({"naver": "empty", "coupang": "empty"})
assert r["outcome"] == "not_found" and r["partial"] is False
async def test_all_blocked_is_not_an_answer():
"""전부 못 봤으면 '없음'이 아니라 '모름'이다 — 재시도해야 한다."""
with pytest.raises(RuntimeError):
await _run({"naver": "blocked", "coupang": "blocked"})
+83 -19
View File
@@ -16,7 +16,7 @@
import asyncio
import time
from common.enums import JobType
from common.enums import JobType, SourceState
from common.logger import LOG
from services.metrics import SearchMetrics
from services.search.contract import SearchAdapter, NormalizedProduct
@@ -40,6 +40,20 @@ def _reap_abandoned(task: asyncio.Task):
LOG.d(f"[fallback] 데드라인 초과 태스크 종료(무시): {type(ex).__name__}")
def _finalize_states(per_source: dict, matched: list[NormalizedProduct]) -> dict:
"""수집 성공 소스의 상태를 **매칭 결과로 확정**한다(제자리 수정 후 반환).
수집 단계에선 '가져왔다'까지만 알 수 있다. '같은 상품이었나'는 AI 판정을 거쳐야 알므로
여기서 MATCHED / NO_MATCH 를 가른다. 실패 상태(BLOCKED·EMPTY 등)는 이미 확정이라 건드리지 않는다.
"""
hit = {p.source for p in matched}
collected = SourceState.MATCHED.name.lower()
for src, info in per_source.items():
if info.get("state") == collected and src not in hit:
info["state"] = SourceState.NO_MATCH.name.lower()
return per_source
def _price_snapshot(matched: list[NormalizedProduct]) -> dict:
"""매칭 목록에서 소스별 최저가 + 전체 최저가 스냅샷을 만든다(price_history 기록용)."""
def lowest(src):
@@ -87,10 +101,20 @@ def build_search_handler(
use = list(sources) if sources else list(adapters.keys())
fallbacks = fallback_adapters or {}
async def _record_history(product_code: str, job_id, outcome: str, matched: list):
async def _record_history(product_code: str, job_id, outcome: str, matched: list,
sources: dict | None = None):
"""price_history 1행 기록.
sources 를 함께 남기는 게 중요하다 — by_mall 은 **가격이 있는 몰만** 담으므로, 어떤 몰이
빠졌을 때 '거기엔 없더라'인지 '거기를 못 봤다'인지 이 값 없이는 알 수 없다.
partial 은 여기서 판단해 사실로 넘긴다(소비자가 상태 분류 규칙을 알 필요 없게).
"""
if history is None:
return
event = {"product_code": product_code, "job_id": job_id, "outcome": outcome, **_price_snapshot(matched)}
confirmed = {s.name.lower() for s in SourceState if s.confirmed}
partial = any((i or {}).get("state") not in confirmed for i in (sources or {}).values())
event = {"product_code": product_code, "job_id": job_id, "outcome": outcome,
"sources": sources or None, "partial": partial, **_price_snapshot(matched)}
try:
await history.record(event)
except Exception as ex:
@@ -109,19 +133,29 @@ def build_search_handler(
raise
async def _search_round(query: str, metrics: SearchMetrics):
"""한 라운드: 모든 소스 동시 검색 → (products, per_source, tech_failed). 소스별 시간/바이트 계측."""
"""한 라운드: 모든 소스 동시 검색 → (products, per_source, ok_sources). 소스별 시간/바이트 계측.
ok_sources 는 **정상 응답한 소스 목록**이다. 예전엔 '하나라도 실패했나'(bool)만 봤는데,
그러면 한 소스가 막혔을 때 다른 소스가 멀쩡히 가져온 결과까지 버리게 된다(아래 호출부 참고).
"""
results = await asyncio.gather(*[_timed_search(adapters[s], query, s, metrics, False) for s in use],
return_exceptions=True)
products, per_source, tech_failed = [], {}, False
products, per_source, ok_sources = [], {}, []
for src, res in zip(use, results):
if isinstance(res, Exception):
tech_failed = True
per_source[src] = {"error": f"{type(res).__name__}: {res}"}
LOG.w(f"[{src}] 검색 실패: {type(res).__name__}: {res}")
# ⚠️ 예외를 문자열로만 남기면 '그 몰에 없었다'와 '그 몰을 못 봤다'가 같아진다.
# AdapterError 는 이미 state 로 그걸 알고 있으므로 **구조화해서 보존**한다.
# (AdapterError 가 아닌 예외 = 우리 코드 버그 → 못 본 것으로 본다)
state = getattr(res, "state", None) or SourceState.UNAVAILABLE
per_source[src] = {"state": state.name.lower(), "error": f"{type(res).__name__}: {res}"}
LOG.w(f"[{src}] 검색 실패({state.name}): {type(res).__name__}: {res}")
if state.confirmed:
ok_sources.append(src) # EMPTY = 봤는데 없던 것 → '정상 응답'으로 센다
else:
products.extend(res)
per_source[src] = {"count": len(res)}
return products, per_source, tech_failed
per_source[src] = {"state": SourceState.MATCHED.name.lower(), "count": len(res)}
ok_sources.append(src)
return products, per_source, ok_sources
async def _match(target: dict, products: list, base_price, metrics: SearchMetrics):
"""필터 → (있으면) AI 같은상품 판정 → 매칭 후보. AI 토큰은 metrics 에 누적.
@@ -214,12 +248,14 @@ def build_search_handler(
rounds_done = 0
last_stages, last_sources = [], {}
last_ok, last_failed = [], []
async for label, query in _round_queries(base_query, target, metrics):
if rounds_done >= max_rounds:
break
rounds_done += 1
products, per_source, tech_failed = await _search_round(query, metrics)
products, per_source, ok_sources = await _search_round(query, metrics)
failed_sources = [s for s in use if s not in ok_sources]
candidates, stages = apply_filters(products, base_price=base_price)
if judge is not None and candidates:
verdicts = await judge.judge(target, candidates)
@@ -227,7 +263,9 @@ def build_search_handler(
matched = [c for c, v in zip(candidates, verdicts) if v.is_match]
stages.append({"stage": "ai_match", "in": len(candidates), "out": len(matched)})
candidates = matched
_finalize_states(per_source, candidates) # 수집만 된 소스를 matched/no_match 로 확정
last_stages, last_sources = stages, per_source
last_ok, last_failed = ok_sources, failed_sources
if candidates: # 찾음 → 오픈마켓 폴백 보강 후 종료
before = len(candidates)
@@ -236,20 +274,46 @@ def build_search_handler(
stages.append({"stage": "fallback_crawl", "in": before, "out": len(candidates)})
result = rank_result(candidates, len(products), stages, top_n)
result.update(outcome="found", query=query, round=label, rounds_tried=rounds_done,
sources=per_source, metrics=metrics.snapshot())
await _record_history(cache_key, job.get("job_id"), "found", candidates)
sources=per_source, sources_ok=ok_sources, sources_failed=failed_sources,
partial=bool(failed_sources), metrics=metrics.snapshot())
if failed_sources:
LOG.w(f"[partial] {failed_sources} 없이 결과를 냈습니다 — 그 몰의 더 싼 값은 못 봤을 수 있습니다")
await _record_history(cache_key, job.get("job_id"), "found", candidates, per_source)
return result
if tech_failed: # 0매칭인데 소스가 죽어 있었음 → '없음'이라 단정 불가 → 기술 재시도
raise RuntimeError(f"기술적 실패로 0매칭(round={label}) — 잡 재시도: {per_source}")
# 0매칭 + 일부 소스 실패. **살아있는 소스가 하나라도 있으면 그 결과로 진행한다** —
# 한 소스가 막혔다고 다른 소스가 멀쩡히 가져온 결과까지 버리면 사용자는 아무것도 못 받는다.
# (실측 2026-08-06: 쿠팡이 막힌 동안 네이버가 40건씩 가져왔는데도 잡이 전부 DEAD 로 갔고,
# DEAD 는 price_history 에 행을 안 남겨 프론트가 '탐색 중'에서 멈췄다)
# 전부 죽었을 때만 '없음'이라 단정할 수 없으므로 재시도한다.
if not ok_sources:
# 마지막 시도면 재시도해도 갈 곳이 없다(다음은 DEAD). DEAD 는 price_history 에 행을
# 남기지 않아, 이를 폴링하는 소비자(negodata 최저가 모달)가 결과를 영영 못 받고
# '탐색 중'에서 멈춘다(2026-08-06 실측). 잡을 죽이는 대신 **실패를 결과로 기록**해
# 화면이 '검색 실패'를 보여줄 수 있게 한다.
if job.get("attempts", 0) >= job.get("max_attempts", 3):
LOG.w(f"[{cache_key}] 모든 소스 실패 + 재시도 소진 → error 로 종료(이력은 남긴다)")
result = rank_result([], 0, stages, top_n)
result.update(outcome="error", query=query, rounds_tried=rounds_done,
sources=per_source, sources_ok=[], sources_failed=failed_sources,
partial=True, metrics=metrics.snapshot())
await _record_history(cache_key, job.get("job_id"), "error", [], per_source)
return result
raise RuntimeError(f"모든 소스 실패로 0매칭(round={label}) — 잡 재시도: {per_source}")
# 모든 라운드 클린 0매칭 → 정상 not_found 종료
if neg_cache is not None:
# 모든 라운드 0매칭 → not_found 로 정상 종료
# 단, 일부 소스가 막혀 있었다면 **네거티브 캐시에 넣지 않는다** — 그 소스엔 있었을 수 있는데
# '없음'으로 굳혀버리면 TTL 동안 재검색이 막힌다(사용자가 '다시 검색'을 눌러도 캐시 히트).
partial = bool(last_failed)
if neg_cache is not None and not partial:
await neg_cache.put(cache_key, reason=f"not_found after {rounds_done} rounds")
result = rank_result([], 0, last_stages, top_n)
result.update(outcome="not_found", query=base_query, rounds_tried=rounds_done,
sources=last_sources, metrics=metrics.snapshot())
await _record_history(cache_key, job.get("job_id"), "not_found", [])
sources=last_sources, sources_ok=last_ok, sources_failed=last_failed,
partial=partial, metrics=metrics.snapshot())
if partial:
LOG.w(f"[partial] {last_failed} 없이 not_found — 네거티브 캐시는 건너뜁니다(그 몰엔 있었을 수 있음)")
await _record_history(cache_key, job.get("job_id"), "not_found", [], last_sources)
return result
return handler
@@ -136,8 +136,16 @@ class item_internet_lowest_prices(MainTableMixin, MAIN_BASE):
lp_url = Column(String, nullable=True) # 찾은 판매 페이지 링크(TEXT) — 근거 검증용
# 몰별 최저가 스냅샷 — lps_db.price_history.by_mall 을 그대로 미러링한다(열린 스키마).
# [{source, mall_name, price, shipping_fee, shipping_type, name, detail_url}, ...] 가격 오름차순.
# 매칭된 몰만 들어오므로, 특정 몰이 없으면 그 몰은 빈손이었다는 뜻이다(네이버 실패/쿠팡만 성공 구분).
# 매칭된 몰만 들어온다. 그래서 **특정 몰이 없는 이유**는 여기서 알 수 없다 —
# '그 몰엔 없었다'인지 '그 몰을 못 봤다(차단)'인지는 아래 sources 가 답한다.
by_mall = Column(JSONB, nullable=True)
# 몰별 확인 상태 — lps_db.price_history.sources 미러링(열린 스키마).
# {"naver": {"state": "matched", "count": 40}, "coupang": {"state": "blocked", "error": "..."}}
# state 값 정의는 lps/docs/result-states.md (LPS common.enums.SourceState).
sources = Column(JSONB, nullable=True)
# 못 본 몰이 있어 결과가 최종이 아님. LPS 가 판단해 내려준 사실을 그대로 싣는다 —
# 화면이 '어떤 상태가 확인된 것인가'를 다시 판정하면 상태 정의가 두 곳으로 흩어진다.
partial = Column(Boolean, nullable=False, server_default=text("false"))
crawl_end_time = Column(DateTime(timezone=True), nullable=False) # 수집 완료 시각(=price_history.created_at, 워터마크 기준)
+156
View File
@@ -0,0 +1,156 @@
from abc import ABC, abstractmethod
from typing import Tuple
from sqlalchemy import and_, asc, column, desc, func, select, table
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import nego_cards, wild_cards
from common.enums import ErrorType
# 학습(learning)·앵커링(anchoring) 스키마는 agent·anchoring 서비스 소유라 negodata ORM 에 없다.
# 조회 전용이므로 필요한 컬럼만 경량 정의한다 — 이 값들의 주인은 negodata 가 아니다(쓰기 금지).
_EXPERIENCE_LOGS = table(
"experience_logs",
column("company_id"), column("session_id"), column("card_id"), column("reward"),
column("settled_price"), column("is_invalidated"), column("created_at"),
column("turn"),
schema="learning",
)
_ANCHORING_CURRENT = table(
"current_values",
column("company_id"), column("supplier_type"), column("price_range_index"),
column("anchoring_value"), column("last_adjusted_at"),
schema="anchoring",
)
_ANCHORING_HISTORY = table(
"value_history",
column("company_id"), column("supplier_type"), column("price_range_index"),
column("anchoring_value_before"), column("anchoring_value_after"),
column("sample_count"), column("success_count"), column("success_rate"), column("created_at"),
schema="anchoring",
)
def _valid(company_id) -> list:
"""유효 학습 기록 — 무효화 표시된 행은 뺀다(협상 취소·재생성 시 agent 가 표시)."""
return [
_EXPERIENCE_LOGS.c.company_id == company_id,
_EXPERIENCE_LOGS.c.is_invalidated == False, # noqa: E712
]
class ILearningCRUD(ABC):
@abstractmethod
async def learning_summary(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, tuple]:
pass
@abstractmethod
async def card_usage(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def card_names(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def anchoring_current(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def anchoring_history(self, cdb: AsyncSession, company_id, limit: int) -> Tuple[ErrorType, list]:
pass
class LearningCRUD(ILearningCRUD):
async def learning_summary(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, tuple]:
"""(학습 협상 수, 기록 수, 타결 협상 수, 마지막 학습 시각)."""
query = select(
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id)),
func.count(),
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id))
.filter(_EXPERIENCE_LOGS.c.settled_price.isnot(None)),
func.max(_EXPERIENCE_LOGS.c.created_at),
).where(and_(*_valid(company_id)))
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "learning_summary failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows:
return err_type, (0, 0, 0, None)
return ErrorType.SUCCESS, tuple(rows[0])
async def card_usage(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
"""카드별 사용 현황 — (카드번호, 사용 협상 수, 사용 횟수, 평균 라운드, 마지막 사용).
협상 결과(타결·가격)는 카드 한 장의 성과로 나눌 수 없어 다루지 않는다 — 한 협상에 여러 장이
나가 어느 장의 몫인지 가릴 근거가 없고, 카드 배정도 국면에 따라 정해져 무작위가 아니다.
평균 라운드 = 그 카드가 협상의 몇 번째 라운드에 나갔는지(설정한 국면과 실제가 맞는지 대조).
"""
query = (
select(
_EXPERIENCE_LOGS.c.card_id,
func.count(func.distinct(_EXPERIENCE_LOGS.c.session_id)),
func.count(),
func.avg(_EXPERIENCE_LOGS.c.turn),
func.max(_EXPERIENCE_LOGS.c.created_at),
)
.where(and_(*_valid(company_id), _EXPERIENCE_LOGS.c.card_id.isnot(None)))
.group_by(_EXPERIENCE_LOGS.c.card_id)
.order_by(desc(func.count()))
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "card_usage failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows or [])
async def card_names(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
"""카드번호 → (번호, 이름, 와일드 여부, 카드 PK). 학습 로그의 card_id 가 카드번호 문자열이라
상세 화면(/cards?detail=<PK>) 으로 보내려면 PK 를 같이 들고 와야 한다.
UNION 은 실행기가 SELECT 로 인정하지 않아 두 번 나눠 조회한다.
"""
out = []
for model, pk, is_wild in ((nego_cards, nego_cards.nego_card_id, 0), (wild_cards, wild_cards.wild_card_id, 1)):
query = select(model.number, model.name, pk).where(model.deleted == False) # noqa: E712
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "card_names failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
out.extend((number, name, is_wild, card_id) for number, name, card_id in (rows or []))
return ErrorType.SUCCESS, out
async def anchoring_current(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
"""현재 앵커링 값 — (협력사유형, 가격대 구간, 값, 마지막 조정 시각). 셀 = 유형 × 가격대."""
query = (
select(
_ANCHORING_CURRENT.c.supplier_type,
_ANCHORING_CURRENT.c.price_range_index,
_ANCHORING_CURRENT.c.anchoring_value,
_ANCHORING_CURRENT.c.last_adjusted_at,
)
.where(_ANCHORING_CURRENT.c.company_id == company_id)
.order_by(asc(_ANCHORING_CURRENT.c.supplier_type), asc(_ANCHORING_CURRENT.c.price_range_index))
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "anchoring_current failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows or [])
async def anchoring_history(self, cdb: AsyncSession, company_id, limit: int) -> Tuple[ErrorType, list]:
"""앵커링 조정 이력(최근순) — 조정마다 표본 수·성공률·값 변화가 남는다."""
query = (
select(
_ANCHORING_HISTORY.c.supplier_type,
_ANCHORING_HISTORY.c.price_range_index,
_ANCHORING_HISTORY.c.anchoring_value_before,
_ANCHORING_HISTORY.c.anchoring_value_after,
_ANCHORING_HISTORY.c.sample_count,
_ANCHORING_HISTORY.c.success_count,
_ANCHORING_HISTORY.c.success_rate,
_ANCHORING_HISTORY.c.created_at,
)
.where(_ANCHORING_HISTORY.c.company_id == company_id)
.order_by(desc(_ANCHORING_HISTORY.c.created_at))
.limit(limit)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "anchoring_history failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows or [])
+5 -1
View File
@@ -29,7 +29,9 @@ _price_history = table(
column("naver_url"),
column("coupang_name"), # 쿠팡 최저가 상품명/링크
column("coupang_url"),
column("by_mall"), # 몰별 최저가 스냅샷(JSONB 배열) — 어느 몰이 건졌고 어느 쪽이 빈손인지
column("by_mall"), # 몰별 최저가 스냅샷(JSONB 배열) — 가격이 **있는** 몰만
column("sources"), # 몰별 확인 상태 — 빠진 몰이 '없었다'인지 '못 봤다'인지는 여기에만 있다
column("partial"), # 못 본 몰이 있어 결과가 최종이 아님(LPS 판단 결과)
column("created_at"),
)
@@ -118,6 +120,8 @@ class LpsSyncCRUD(ILpsSyncCRUD):
_price_history.c.coupang_name,
_price_history.c.coupang_url,
_price_history.c.by_mall,
_price_history.c.sources,
_price_history.c.partial,
_price_history.c.created_at,
).order_by(_price_history.c.created_at.asc())
if since is not None:
+26 -3
View File
@@ -55,6 +55,10 @@ class IQuotationCRUD(ABC):
async def get_company_settings(self, cdb: AsyncSession, user_id) -> dict:
pass
@abstractmethod
async def get_company_brand(self, cdb: AsyncSession, user_id) -> Tuple[str, dict]:
pass
@abstractmethod
async def add_rows(self, cdb: AsyncSession, obj_list: list) -> ErrorType:
pass
@@ -408,6 +412,24 @@ class QuotationCRUD(IQuotationCRUD):
LOG.e_no_callstack(ex)
return {}
async def get_company_brand(self, cdb: AsyncSession, user_id):
# 이 유저가 속한 회사의 (이름, settings). 초청 메일 헤더 기본값이 회사명이라 이름까지 같이 읽는다.
try:
query = (
select(companies.name, companies.settings)
.select_from(users)
.join(companies, companies.company_id == users.company_id)
.where(users.user_id == user_id, companies.deleted == False) # noqa: E712
.limit(1)
)
err, rows = await DB_SESSION_MNG.execute(cdb, query)
if err != ErrorType.SUCCESS or not rows:
return "", {}
return rows[0][0] or "", rows[0][1] or {}
except Exception as ex:
LOG.e_no_callstack(ex)
return "", {}
async def get_item_companies(self, cdb: AsyncSession, item_ids) -> Tuple[ErrorType, dict]:
"""item_id -> company_id(소유 회사) 매핑. 앵커링 칸(회사×유형×가격구간) 해석 입력."""
try:
@@ -681,13 +703,14 @@ class QuotationCRUD(IQuotationCRUD):
return ErrorType.DB_RUN_FAILED, 0
async def list_sessions_status(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, name, target_price, anchoring_price). 삭제 제외.
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, name, target_price, anchoring_price, reject_price). 삭제 제외.
공급사가 지워졌어도 세션 집계엔 포함되도록 outerjoin(이때 name 은 None).
target/anchoring 은 마감 가격게이트 입력(견적당 상품 1개라 세션 공통값)."""
target/anchoring 은 마감 가격게이트 입력(견적당 상품 1개라 세션 공통값).
reject_price 는 거부 협력사의 공급 희망 가격 — 자동 마감 판정엔 안 쓰고 수동 직접 낙찰 후보에서만 본다."""
try:
query = (
select(sessions.status, sessions.supplier_id, sessions.bid_price, suppliers.name,
sessions.target_price, sessions.anchoring_price)
sessions.target_price, sessions.anchoring_price, sessions.reject_price)
.outerjoin(suppliers, suppliers.supplier_id == sessions.supplier_id)
.where(sessions.quotation_id == qt_id, sessions.deleted == False) # noqa: E712
)
+5 -2
View File
@@ -76,14 +76,17 @@ class StatisticsCRUD(IStatisticsCRUD):
async def winning_sessions(self, cdb: AsyncSession, company_id, owner, since) -> Tuple[ErrorType, list]:
# 낙찰 마감 견적의 '낙찰 세션'(supplier_id=preferred_sp_id) 행 — 절감/추이/유형/카테고리/앵커도달률의 단일 원천.
# 파생: 저장 안 하고 조회 때 조인. category 는 items LEFT JOIN(자유텍스트·NULL 허용).
# 계약가는 coalesce(투찰가, 거부 시 공급 희망가) — 결렬 건을 담당자가 직접 낙찰하면 bid_price 가 없어
# 절감 집계에서 통째로 빠지기 때문. 이름은 bid_price 로 유지해 statistics_service 는 그대로 쓴다.
try:
award_price = func.coalesce(sessions.bid_price, sessions.reject_price).label("bid_price")
stmt = (
select(
quotations.updated_at,
quotations.type,
items.category,
sessions.target_price,
sessions.bid_price,
award_price,
sessions.anchoring_price,
)
.select_from(quotations)
@@ -92,7 +95,7 @@ class StatisticsCRUD(IStatisticsCRUD):
and_(
sessions.quotation_id == quotations.qt_id,
sessions.supplier_id == quotations.preferred_sp_id,
sessions.bid_price.isnot(None),
or_(sessions.bid_price.isnot(None), sessions.reject_price.isnot(None)),
sessions.deleted == False, # noqa: E712
),
)
+1
View File
@@ -12,4 +12,5 @@ openpyxl
httpx
apscheduler>=3.10
azure-communication-email>=1.0 # 초청 메일 1순위 발송 채널(ACS Email)
aiohttp>=3.9 # azure aio 클라이언트(EmailClient.aio)의 HTTP 전송 계층
aiosmtplib>=3.0 # 초청 메일 폴백(SMTP)
+2
View File
@@ -20,6 +20,7 @@ import router.v1.card.card
import router.v1.quotation.quotation
import router.v1.quotation_setting.quotation_setting
import router.v1.dashboard.dashboard
import router.v1.learning.learning
import router.v1.statistics.statistics
import router.v1.notification.notification
import router.v1.renegotiation.renegotiation
@@ -79,5 +80,6 @@ app.include_router(router.v1.quotation.quotation.router)
app.include_router(router.v1.quotation_setting.quotation_setting.router)
app.include_router(router.v1.dashboard.dashboard.router)
app.include_router(router.v1.statistics.statistics.router)
app.include_router(router.v1.learning.learning.router)
app.include_router(router.v1.notification.notification.router)
app.include_router(router.v1.renegotiation.renegotiation.router)
@@ -70,3 +70,13 @@ class Req_UpdateCompanySettings(CompanySettingsProtocol):
class Res_CompanySettings(Res_WebPacketProtocol):
settings: Optional[dict] = None
class Req_PreviewInviteEmail(CompanySettingsProtocol):
# 저장 전 편집값으로 초청 메일을 렌더한다. settings.branding 서브키 중 email_* 만 쓴다.
branding: dict = {}
class Res_PreviewInviteEmail(Res_WebPacketProtocol):
subject: str = ""
html: str = ""
@@ -3,7 +3,7 @@ from fastapi import APIRouter, Depends
from common.models.gmodel import UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, RequireOwner
from services.company_settings_service import CompanySettingsService
from .protocol import Req_UpdateCompanySettings, Res_CompanySettings
from .protocol import Req_PreviewInviteEmail, Req_UpdateCompanySettings, Res_CompanySettings, Res_PreviewInviteEmail
# 회사별 커스터마이징 설정. 조회=로그인 유저 전원(앱 부팅 시 브랜딩/라벨 로드), 수정=최고관리자(OWNER) 전용.
router = APIRouter(prefix="/v1/company/settings", tags=["CompanySettings"], responses={404: {"description": "Not found"}})
@@ -19,3 +19,11 @@ async def update_settings(
req: Req_UpdateCompanySettings, service: CompanySettingsService = Depends(), owner: UserInfo = Depends(RequireOwner)
):
return RemoveNoneResponse(await service.update_settings(owner.company_id, req))
# 저장 전 편집값을 그대로 렌더한다(쓰기 없음) — 로그인만 요구. 회사명은 토큰의 회사로 채운다.
@router.post(path="/email-preview", response_model=Res_PreviewInviteEmail, summary="협상 초청 메일 미리보기")
async def preview_invite_email(
req: Req_PreviewInviteEmail, service: CompanySettingsService = Depends(), user: UserInfo = Depends(IsValidAccessToken)
):
return RemoveNoneResponse(await service.preview_invite_email(user.company_id, req))
+8 -1
View File
@@ -145,9 +145,16 @@ class LowestPriceEntry(WebPacketProtocol):
fail_reason: Optional[str] = None
lp_name: Optional[str] = None # 찾은 상품명(판매 페이지 기준) — 근거 검증용
lp_url: Optional[str] = None # 찾은 판매 페이지 링크
# 몰별 최저가 스냅샷(가격 오름차순). 매칭된 몰만 들어오므로, 없는 몰은 그 회차에 빈손이었다는 뜻.
# 몰별 최저가 스냅샷(가격 오름차순). **가격이 있는 몰만** 들어온다 —
# 그래서 없는 몰이 '거기엔 없었다'인지 '거기를 못 봤다'인지는 아래 sources 가 답한다.
# [{source: 'naver'|'coupang'|…, mall_name, price, shipping_fee, shipping_type, name, detail_url}]
by_mall: Optional[list[dict]] = None
# 몰별 확인 상태 — {"naver": {"state": "matched"}, "coupang": {"state": "blocked"}}.
# 화면은 이걸 셋으로 접어 쓴다: 가격 / '–'(없음) / '확인 못함'(미확인).
# state 정의는 lps/docs/result-states.md.
sources: Optional[dict] = None
# 못 본 몰이 있어 결과가 최종이 아님. LPS 가 판단한 사실이라 화면은 그대로 쓰면 된다.
partial: bool = False
crawl_end_time: Optional[datetime] = None
Whitespace-only changes.
@@ -0,0 +1,19 @@
from fastapi import APIRouter, Depends
from common.models.gmodel import UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
from services.learning_service import LearningService
from .protocol import Res_AnchoringStatus, Res_LearningStatus
# 협상 학습 현황 — agent(협상카드 학습)·anchoring(앵커링 조정)이 쌓은 결과를 회사 스코프로 읽는다.
router = APIRouter(prefix="/v1/learning", tags=["Learning"], responses={404: {"description": "Not found"}})
@router.get(path="/cards", response_model=Res_LearningStatus, summary="협상카드 학습 현황")
async def get_learning_status(service: LearningService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_learning_status(user_info.company_id))
@router.get(path="/anchoring", response_model=Res_AnchoringStatus, summary="앵커링 현황·조정 이력")
async def get_anchoring_status(service: LearningService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_anchoring_status(user_info.company_id))
@@ -0,0 +1,63 @@
from datetime import datetime
from typing import Optional
from pydantic import Field
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
class LearningProtocol(WebPacketProtocol):
pass
class LearningKpi(LearningProtocol):
learned_sessions: int = 0 # 학습에 반영된 협상 수
records: int = 0 # 학습 기록 수(카드 선택 1회 = 1건)
used_cards: int = 0 # 한 번이라도 나간 카드 수
unused_cards: int = 0 # 아직 한 번도 안 나간 카드 수
top3_share: float = 0.0 # 상위 3장이 차지하는 사용 비중 — 쏠림 정도
last_learned_at: Optional[datetime] = None
class CardUsageRow(LearningProtocol):
number: str # 카드번호(NGC-001 등)
name: Optional[str] = None
card_id: Optional[str] = None # 카드 PK — 협상카드 상세(/cards?detail=) 링크용
type: str = "nego" # nego | wild
used_sessions: int = 0 # 이 카드가 나간 협상 수
uses: int = 0 # 총 사용 횟수
share: float = 0.0 # 전체 카드 사용 중 이 카드의 비중
avg_turn: float = 0.0 # 평균 몇 번째 라운드에 나갔는지 — 설정한 국면과 대조용
last_used_at: Optional[datetime] = None
class AnchoringCell(LearningProtocol):
supplier_type: int = 0
supplier_type_label: str = "미지정"
price_range_index: int = 0 # 목표가 기준 가격대 구간
price_range_label: str = "" # 그 구간의 실제 금액 범위(화면 표기용)
anchoring_value: float = 0.0 # 앵커링 인하폭(‰ — 10 = 1%)
last_adjusted_at: Optional[datetime] = None
class AnchoringHistoryRow(LearningProtocol):
supplier_type_label: str = "미지정"
price_range_index: int = 0
price_range_label: str = ""
value_before: float = 0.0
value_after: float = 0.0
sample_count: int = 0 # 조정 판단에 쓴 협상 표본 수
success_count: int = 0
success_rate: float = 0.0
created_at: Optional[datetime] = None
class Res_LearningStatus(Res_WebPacketProtocol):
kpi: LearningKpi = Field(default_factory=LearningKpi)
cards: list[CardUsageRow] = []
class Res_AnchoringStatus(Res_WebPacketProtocol):
cells: list[AnchoringCell] = []
history: list[AnchoringHistoryRow] = []
adjusted_count: int = 0
@@ -3,6 +3,7 @@ from uuid import UUID
from fastapi import APIRouter, Depends, Query
from common.enums import UserRole
from common.models.gmodel import PageParams, UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
from services.quotation import QuotationService
@@ -42,7 +43,9 @@ async def list_quotations(
mine: bool = Query(False, description="내 견적만 보기(작성자=로그인 유저)"),
pg: PageParams = Depends(),
):
owner = user_info.user_id if mine else None
# 일반(USER)은 mine 파라미터와 무관하게 본인 견적만 — 타 담당자 견적 조회는 OWNER 이상만.
force_mine = (user_info.role or 0) < UserRole.OWNER.value
owner = user_info.user_id if (mine or force_mine) else None
return RemoveNoneResponse(await service.list_quotations(user_info.company_id, owner, search, status, type, start_from, start_to, pg))
@@ -84,12 +87,12 @@ async def regenerate_quotation(
# ----- 견적 상세 (FK로 연결된 하위 데이터 / 일부는 모델 미존재로 스텁) -----
@router.get(path="/{qt_id}/status", response_model=Res_QuotationStatus, summary="견적 상태 조회")
async def get_quotation_status(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_status(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.get_status(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.get(path="/{qt_id}/sessions", response_model=Res_QuotationSessions, summary="참여현황")
async def get_quotation_sessions(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.list_sessions(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.list_sessions(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.post(path="/{qt_id}/notify", response_model=Res_NotifySessions, summary="협상 초청 메일 발송")
@@ -99,12 +102,12 @@ async def notify_quotation(qt_id: UUID, service: QuotationService = Depends(), u
@router.get(path="/session/{session_id}/chat", response_model=Res_SessionChat, summary="채팅 상세")
async def get_session_chat(session_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.list_chats(str(session_id), user_info.company_id))
return RemoveNoneResponse(await service.list_chats(str(session_id), user_info.company_id, user_info.user_id, user_info.role))
@router.get(path="/session/{session_id}/target-breakdown", response_model=Res_TargetBreakdown, summary="세션 목표가 산정내역")
async def get_target_breakdown(session_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_target_breakdown(str(session_id), user_info.company_id))
return RemoveNoneResponse(await service.get_target_breakdown(str(session_id), user_info.company_id, user_info.user_id, user_info.role))
@router.post(path="/session/{session_id}/notify", response_model=Res_NotifySessions, summary="세션 초청 메일 재발송")
@@ -114,12 +117,12 @@ async def notify_session(session_id: UUID, service: QuotationService = Depends()
@router.get(path="/{qt_id}/result", response_model=Res_QuotationResult, summary="낙찰 결과")
async def get_quotation_result(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_result(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.get_result(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.get(path="/{qt_id}/cards", response_model=Res_QuotationCards, summary="견적 사용 카드")
async def get_quotation_cards(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.list_cards(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.list_cards(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.delete(path="/delete/{qt_id}", response_model=Res_DeleteQuotation, summary="견적 삭제")
@@ -130,4 +133,4 @@ async def delete_quotation(qt_id: UUID, service: QuotationService = Depends(), u
# ----- 단건 조회 (정적/하위 경로 뒤에 선언) -----
@router.get(path="/{qt_id}", response_model=Res_Quotation, summary="견적 조회")
async def get_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_quotation(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.get_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@@ -1,12 +1,21 @@
import uuid
from datetime import timedelta
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import companies
from common.enums import DBWRType, ErrorType
from common.utils.gtime import GTime
from config.server_configs import web_server_config
from crud.user_crud import IUserCRUD, UserCRUD
from router.v1.company.protocol import Req_UpdateCompanySettings, Res_CompanySettings
from router.v1.company.protocol import (
Req_PreviewInviteEmail,
Req_UpdateCompanySettings,
Res_CompanySettings,
Res_PreviewInviteEmail,
)
from services.email import build_invite_email
class CompanySettingsService:
@@ -43,3 +52,25 @@ class CompanySettingsService:
return res
res.settings = req.settings
return res
async def preview_invite_email(self, company_id: str, req: Req_PreviewInviteEmail) -> Res_PreviewInviteEmail:
"""저장 전 branding 편집값을 샘플 견적 데이터로 렌더한다(발송 없음).
실제 발송(services/quotation/invites.py)과 같은 build_invite_email 을 타므로 미리보기=실물.
회사명은 헤더 기본값이라 실발송과 동일하게 채워 보여준다."""
res = Res_PreviewInviteEmail()
_, company = await DB_SESSION_MNG.execute_lambda(
companies.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_company(s, uuid.UUID(company_id)),
)
base = (web_server_config.nego_chat_url or "").rstrip("/")
res.subject, res.html, _ = build_invite_email(
supplier_name="샘플 협력사",
quotation_name="복사용지 A4 80g 외 2건",
qt_number="EST-2026-0801",
end_time=GTime.UTC() + timedelta(days=3),
chat_url=f"{base}/chat?session_id=00000000-0000-0000-0000-000000000000",
company_name=(company.name if company else "") or "",
branding=req.branding,
)
return res
+34 -4
View File
@@ -9,6 +9,7 @@ HTML 본문 템플릿: services/email_templates/*.html ($placeholder 치환).
"""
from __future__ import annotations
import re
from datetime import datetime
from email.message import EmailMessage
from html import escape
@@ -21,6 +22,12 @@ from config.server_configs import mail_config
_KST = ZoneInfo("Asia/Seoul")
# 회사 CI(settings.branding) 미설정 시 기본값 — 설정 화면 placeholder 와 같은 값이어야 한다.
# 색 기본값은 공급사 협상 포털(frontend --brand-600)과 동일 — 메일에서 포털로 이어지는 화면이 한 브랜드로 보이게.
_DEFAULT_EMAIL_COLOR = "#3182f6"
_DEFAULT_EMAIL_HEADER = "NEGODATA"
_DEFAULT_EMAIL_GREETING = "아래 견적 건의 협상에 참여해 주세요."
# HTML 본문은 코드에 박지 않고 파일에서 읽는다(모듈 로드 시 1회). $placeholder 는 string.Template 로 치환.
_TEMPLATE_DIR = Path(__file__).parent / "email_templates"
_INVITE_HTML = Template((_TEMPLATE_DIR / "invite_email.html").read_text(encoding="utf-8"))
@@ -96,17 +103,27 @@ def build_invite_email(
qt_number: str,
end_time: datetime | None,
chat_url: str,
email_header: str | None = None,
company_name: str = "",
branding: dict | None = None,
) -> tuple[str, str, str]:
"""협상 초청 메일 (제목/HTML/텍스트) 생성.
목표가·앵커링가는 협상 전략 값이라 메일에 담지 않는다(공급사에게 노출 금지).
공급사는 링크로 협상 화면에 진입해 입찰한다.
branding = companies.settings.branding — 헤더는 회사 CI(logo_url·service_name)를
그대로 쓴다(메일 전용 이중 설정 금지). 메일 전용 키는 인사 문구(email_greeting) 하나뿐.
헤더는 로고 있으면 로고, 없으면 service_name → 회사명(company_name) → NEGODATA 텍스트 —
공급사에겐 솔루션명보다 발주사가 보여야 한다. 색은 회사별 커스텀 없이 솔루션 기본색 고정.
레이아웃은 고정이고 값만 갈아끼우므로, 어떤 값을 넣어도 메일이 깨지지 않는다.
"""
b = branding or {}
sp = supplier_name or "협력사"
deadline = _fmt_deadline(end_time) or "미정"
subject = f"[협상 견적 {qt_number}] {quotation_name} — 협상 참여 요청"
header_name = (b.get("service_name") or "").strip() or (company_name or "").strip() or _DEFAULT_EMAIL_HEADER
greeting = (b.get("email_greeting") or "").strip() or _DEFAULT_EMAIL_GREETING
# HTML 본문은 invite_email.html 에서 읽어 치환. 값은 escape 해 HTML 인젝션 방지(견적명 등은 사용자 입력).
html = _INVITE_HTML.substitute(
supplier_name=escape(sp),
@@ -114,14 +131,27 @@ def build_invite_email(
qt_number=escape(qt_number),
deadline=escape(deadline),
chat_url=escape(chat_url),
email_header=escape(email_header or "NEGODATA"),
brand_color=_DEFAULT_EMAIL_COLOR,
header_content=_header_content(header_name, (b.get("logo_url") or "").strip()),
email_greeting=escape(greeting),
)
text = (
f"{sp} 담당자님, 아래 견적 건의 협상에 참여해 주세요.\n\n"
f"{sp} 담당자님, {greeting}\n\n"
f" - 견적명: {quotation_name}\n"
f" - 견적번호: {qt_number}\n"
f" - 협상 마감: {deadline}\n\n"
f"협상 참여 링크: {chat_url}\n"
f"협상 참여 링크: {chat_url}\n\n"
f"— negotium B2B 구매협상 솔루션\n"
)
return subject, html, text
def _header_content(name: str, logo_url: str) -> str:
"""헤더(흰 배경) 내용물 — 회사 CI 로고가 있으면 이미지(회사명은 alt 로), 없으면 회사명 텍스트. escape 는 여기서 끝낸다."""
if logo_url:
return (
f'<img src="{escape(logo_url)}" alt="{escape(name)}" height="32" '
f'style="display:block;height:32px;max-width:220px;border:0;margin:0 auto;" />'
)
return f'<span style="color:#191f28;font-size:18px;font-weight:800;letter-spacing:-0.4px;">{escape(name)}</span>'
@@ -1,37 +1,43 @@
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f5f7;margin:0;padding:24px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f2f4f6;margin:0;padding:24px 12px;">
<tr>
<td align="center">
<table role="presentation" width="480" cellpadding="0" cellspacing="0" style="width:480px;max-width:480px;background-color:#ffffff;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb;font-family:'Apple SD Gothic Neo',-apple-system,'Segoe UI',Roboto,'Malgun Gothic',sans-serif;">
<table role="presentation" width="480" cellpadding="0" cellspacing="0" style="width:480px;max-width:480px;background-color:#ffffff;border-radius:16px;overflow:hidden;border:1px solid #e5e8eb;font-family:Pretendard,'Apple SD Gothic Neo',-apple-system,'Segoe UI',Roboto,'Malgun Gothic',sans-serif;">
<!-- 헤더 바 -->
<!-- 브랜드 액센트 — 회사 CI 색(primary_color) -->
<tr>
<td style="background-color:#2563eb;padding:18px 28px;">
<span style="color:#ffffff;font-size:16px;font-weight:700;letter-spacing:1px;">$email_header</span>
<td height="4" bgcolor="$brand_color" style="height:4px;font-size:0;line-height:0;">&nbsp;</td>
</tr>
<!-- 헤더 — 회사 CI(로고 있으면 로고, 없으면 회사명) + 솔루션 태그라인. 챗 포털 로그인 락업과 같은 구성 -->
<tr>
<td align="center" style="padding:30px 28px 0 28px;">
$header_content
<p style="margin:10px 0 0 0;font-size:12px;color:#8b95a1;">negotium B2B 구매협상 솔루션</p>
</td>
</tr>
<!-- 본문 -->
<tr>
<td style="padding:32px 28px 4px 28px;">
<h1 style="margin:0 0 10px 0;font-size:20px;font-weight:700;color:#111827;">협상 참여 요청</h1>
<p style="margin:0 0 24px 0;font-size:14px;line-height:1.7;color:#4b5563;">
<strong style="color:#111827;">$supplier_name</strong> 담당자님,<br>
아래 견적 건의 협상에 참여해 주세요.
<h1 style="margin:0 0 10px 0;font-size:20px;font-weight:700;letter-spacing:-0.4px;color:#191f28;">협상 참여 요청</h1>
<p style="margin:0 0 24px 0;font-size:14px;line-height:1.7;color:#4e5968;">
<strong style="color:#191f28;">$supplier_name</strong> 담당자님,<br>
$email_greeting
</p>
<!-- 견적 정보 카드 -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f9fafb;border:1px solid #eef0f3;border-radius:10px;margin-bottom:28px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f9fafb;border:1px solid #e5e8eb;border-radius:12px;margin-bottom:28px;">
<tr>
<td style="padding:14px 16px;font-size:13px;color:#6b7280;width:88px;">견적명</td>
<td style="padding:14px 16px;font-size:13px;color:#111827;font-weight:600;text-align:right;">$quotation_name</td>
<td style="padding:14px 16px;font-size:13px;color:#8b95a1;width:88px;">견적명</td>
<td style="padding:14px 16px;font-size:13px;color:#191f28;font-weight:600;text-align:right;">$quotation_name</td>
</tr>
<tr>
<td style="padding:14px 16px;font-size:13px;color:#6b7280;border-top:1px solid #eef0f3;">견적번호</td>
<td style="padding:14px 16px;font-size:13px;color:#374151;text-align:right;border-top:1px solid #eef0f3;">$qt_number</td>
<td style="padding:14px 16px;font-size:13px;color:#8b95a1;border-top:1px solid #f2f4f6;">견적번호</td>
<td style="padding:14px 16px;font-size:13px;color:#333d4b;text-align:right;border-top:1px solid #f2f4f6;">$qt_number</td>
</tr>
<tr>
<td style="padding:14px 16px;font-size:13px;color:#6b7280;border-top:1px solid #eef0f3;">협상 마감</td>
<td style="padding:14px 16px;font-size:13px;color:#dc2626;font-weight:700;text-align:right;border-top:1px solid #eef0f3;">$deadline</td>
<td style="padding:14px 16px;font-size:13px;color:#8b95a1;border-top:1px solid #f2f4f6;">협상 마감</td>
<td style="padding:14px 16px;font-size:13px;color:#e71c3b;font-weight:700;text-align:right;border-top:1px solid #f2f4f6;">$deadline</td>
</tr>
</table>
@@ -41,9 +47,8 @@
<td align="center">
<table role="presentation" cellpadding="0" cellspacing="0">
<tr>
<td align="center" bgcolor="#2563eb" style="border-radius:8px;">
<!-- TODO: 세션별 협상링크 연결 시 href 를 $$chat_url 로 복원 -->
<a href="https://nego.o2o.kr" style="display:inline-block;padding:14px 34px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;">협상 참여하기 →</a>
<td align="center" bgcolor="$brand_color" style="border-radius:12px;">
<a href="$chat_url" style="display:inline-block;padding:14px 34px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:12px;">협상 참여하기 →</a>
</td>
</tr>
</table>
@@ -56,15 +61,14 @@
<!-- 푸터 -->
<tr>
<td style="padding:18px 28px 26px 28px;">
<p style="margin:0;font-size:11px;line-height:1.7;color:#9ca3af;border-top:1px solid #f0f1f3;padding-top:16px;">
<p style="margin:0;font-size:11px;line-height:1.7;color:#8b95a1;border-top:1px solid #f2f4f6;padding-top:16px;">
버튼이 열리지 않으면 아래 링크를 복사해 접속하세요.<br>
<a href="https://nego.o2o.kr" style="color:#6b7280;word-break:break-all;">https://nego.o2o.kr</a>
<a href="$chat_url" style="color:#4e5968;word-break:break-all;">$chat_url</a>
</p>
</td>
</tr>
</table>
<p style="margin:16px 0 0 0;font-size:11px;color:#b0b4bb;font-family:sans-serif;">본 메일은 협상 견적 시스템에서 자동 발송되었습니다.</p>
</td>
</tr>
</table>
@@ -0,0 +1,123 @@
import uuid
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import quotations
from common.anchoring.constants import UPPER_BOUNDS
from common.enums import DBWRType, ErrorType, SupplierType
from crud.learning_crud import ILearningCRUD, LearningCRUD
from router.v1.learning.protocol import (
AnchoringCell,
AnchoringHistoryRow,
CardUsageRow,
LearningKpi,
Res_AnchoringStatus,
Res_LearningStatus,
)
HISTORY_LIMIT = 50 # 앵커링 조정 이력 표시 개수 — 한 화면에서 훑는 용도
def _price_range_label(index: int) -> str:
"""가격대 인덱스 → 실제 금액 범위. 사다리는 common.anchoring 정본(UPPER_BOUNDS)만 참조한다."""
if index < 0 or index >= len(UPPER_BOUNDS):
return ""
low = UPPER_BOUNDS[index - 1] if index else 0
return f"{low:,}~{UPPER_BOUNDS[index]:,}원"
_SUPPLIER_TYPE_LABEL = {
SupplierType.NONE.value: "미지정",
SupplierType.DISTRIBUTION.value: "유통",
SupplierType.MANUFACTURE.value: "제조",
SupplierType.SOLE_AGENCY.value: "총판",
}
class LearningService:
"""협상 학습 현황 — 협상카드 학습(agent Q-learning)과 앵커링 조정 이력을 읽어 보여준다.
두 값 모두 negodata 가 만드는 값이 아니라 agent·anchoring 서비스가 쌓은 결과다(읽기 전용).
"""
def __init__(self, crud: ILearningCRUD = Depends(LearningCRUD)):
self.crud = crud
async def get_learning_status(self, company_id: str) -> Res_LearningStatus:
"""카드 사용 현황 — 담아둔 카드가 실제로 나가는지, 어느 국면에 나가는지, 쏠리지는 않는지.
협상 성과(타결·가격)는 카드별로 나누지 않는다 — 한 협상에 여러 장이 나가 어느 장의 몫인지
가릴 수 없고, 카드 배정도 무작위가 아니라 국면에 따라 정해지기 때문이다.
"""
res = Res_LearningStatus()
# learning 의 company_id 는 agent 가 테넌트 키를 그대로 넣는 문자열 컬럼이다(UUID 타입 아님).
cid = str(company_id)
sessions, records, _settled, last_at = await self._read(
lambda s: self.crud.learning_summary(s, cid), default=(0, 0, 0, None))
rows = await self._read(lambda s: self.crud.card_usage(s, cid), default=[])
names = await self._read(lambda s: self.crud.card_names(s), default=[])
name_map = {str(number): (name, is_wild, card_pk) for number, name, is_wild, card_pk in names if number}
total_uses = sum(int(uses or 0) for _n, _s, uses, _t, _l in rows) or 1
for card_id, used_sessions, uses, avg_turn, last_used in rows:
number = str(card_id)
name, is_wild, card_pk = name_map.get(number, (None, 0, None))
res.cards.append(CardUsageRow(
number=number,
name=name,
card_id=str(card_pk) if card_pk else None,
type="wild" if is_wild else "nego",
used_sessions=int(used_sessions or 0),
uses=int(uses or 0),
share=round(int(uses or 0) / total_uses, 3),
avg_turn=round(float(avg_turn), 1) if avg_turn is not None else 0.0,
last_used_at=last_used,
))
res.kpi = LearningKpi(
learned_sessions=int(sessions or 0),
records=int(records or 0),
used_cards=len(res.cards),
unused_cards=max(0, len(name_map) - len(res.cards)),
top3_share=round(sum(c.uses for c in res.cards[:3]) / total_uses, 3),
last_learned_at=last_at,
)
return res
async def get_anchoring_status(self, company_id: str) -> Res_AnchoringStatus:
res = Res_AnchoringStatus()
# anchoring 스키마의 company_id 는 UUID 타입 — learning(문자열 테넌트 키)과 다르다.
cid = uuid.UUID(str(company_id))
cells = await self._read(lambda s: self.crud.anchoring_current(s, cid), default=[])
for supplier_type, price_range_index, value, adjusted_at in cells:
res.cells.append(AnchoringCell(
supplier_type=int(supplier_type or 0),
supplier_type_label=_SUPPLIER_TYPE_LABEL.get(int(supplier_type or 0), "미지정"),
price_range_index=int(price_range_index or 0),
price_range_label=_price_range_label(int(price_range_index or 0)),
anchoring_value=float(value) if value is not None else 0.0,
last_adjusted_at=adjusted_at,
))
history = await self._read(lambda s: self.crud.anchoring_history(s, cid, HISTORY_LIMIT), default=[])
for st, pri, before, after, sample, success, rate, created_at in history:
res.history.append(AnchoringHistoryRow(
supplier_type_label=_SUPPLIER_TYPE_LABEL.get(int(st or 0), "미지정"),
price_range_index=int(pri or 0),
price_range_label=_price_range_label(int(pri or 0)),
value_before=float(before) if before is not None else 0.0,
value_after=float(after) if after is not None else 0.0,
sample_count=int(sample or 0),
success_count=int(success or 0),
success_rate=round(float(rate), 3) if rate is not None else 0.0,
created_at=created_at,
))
res.adjusted_count = len(res.history)
return res
async def _read(self, fn, default):
"""crud 한 건 실행 — 실패해도 화면은 떠야 하므로 기본값으로 떨어진다."""
err, rows = await DB_SESSION_MNG.execute_lambda(quotations.DBType(), DBWRType.DB_READ.value, fn)
return rows if err == ErrorType.SUCCESS else default
+10 -3
View File
@@ -159,7 +159,8 @@ class LpsSyncService:
# product_code(uuid=item_id) 검증 — LPS 부하테스트 등 비상품 코드는 조용히 스킵
parsed = []
for code, outcome, final_lowest, final_source, nv_name, nv_url, cp_name, cp_url, by_mall, created_at in rows:
for (code, outcome, final_lowest, final_source, nv_name, nv_url, cp_name, cp_url,
by_mall, sources, partial, created_at) in rows:
try:
iid = uuid.UUID(code)
except (ValueError, AttributeError, TypeError):
@@ -170,7 +171,8 @@ class LpsSyncService:
"naver": (nv_name, nv_url),
"coupang": (cp_name, cp_url),
}.get((final_source or "").lower(), (None, None))
parsed.append((iid, outcome, final_lowest, final_source, src_name, src_url, by_mall, created_at))
parsed.append((iid, outcome, final_lowest, final_source, src_name, src_url,
by_mall, sources, partial, created_at))
err, existing = await DB_SESSION_MNG.execute_lambda(
DBType.MAIN.value, DBWRType.DB_READ.value,
@@ -180,7 +182,8 @@ class LpsSyncService:
return results
history_rows, latest_found = [], {} # latest_found: item_id → (created_at, price)
for item_id, outcome, final_lowest, final_source, src_name, src_url, by_mall, created_at in parsed:
for (item_id, outcome, final_lowest, final_source, src_name, src_url,
by_mall, sources, partial, created_at) in parsed:
if item_id not in existing:
results["skipped_unknown_item"] += 1
continue
@@ -194,6 +197,10 @@ class LpsSyncService:
lp_name=(src_name or None) and src_name[:300],
lp_url=src_url or None,
by_mall=by_mall or None, # 몰별 스냅샷 그대로 미러링 — 몰별 성공/실패 표시용
# 몰별 확인 상태도 그대로 옮긴다. by_mall 에 없는 몰이 '없었다'인지 '못 봤다'인지는
# 이 값에만 있어, 없으면 화면이 두 경우를 구분할 방법이 없다.
sources=sources or None,
partial=bool(partial),
crawl_end_time=created_at, # 워터마크 기준값 — price_history.created_at 그대로 보존
))
results["found" if found else "not_found"] += 1
+20 -10
View File
@@ -10,6 +10,17 @@ from router.v1.quotation.protocol import Res_Quotation
from services.notification import create_notification
def _award_price(row) -> Optional[int]:
"""직접 낙찰 시 계약 기준가 — 타결했으면 투찰가, 협상이 거부로 끝났으면 그때 써낸 공급 희망 가격.
둘 다 없으면(가격을 한 번도 안 낸 협력사) None → 낙찰 후보가 아니다.
자동 마감 판정(close_and_decide)은 이 함수를 쓰지 않는다 — 자동 낙찰은 투찰가만 본다."""
if row.status == SessionStatus.DONE.value and row.bid_price is not None:
return int(row.bid_price)
if row.status == SessionStatus.REJECTED.value and row.reject_price is not None:
return int(row.reject_price)
return None
class ClosingMixin:
@staticmethod
def _pick_winner(done_rows) -> tuple[Optional[dict], Optional[dict]]:
@@ -159,7 +170,9 @@ class ClosingMixin:
async def award_quotation(self, qt_id: str, company_id, user_id, role, winner_supplier_id) -> Res_Quotation:
"""[프론트] 개찰(낙찰자 미정 마감) 견적을 담당자가 직접 낙찰 처리한다.
투찰한 협상완료(DONE) 세션 중 고른 협력사를 낙찰자로 박고 close_reason 을 AWARDED 로 바꾼다(직접 낙찰).
가격을 써낸 세션 중 고른 협력사를 낙찰자로 박고 close_reason 을 AWARDED 로 바꾼다(직접 낙찰).
후보는 투찰한 협상완료(DONE) + 공급 희망 가격을 남긴 협상거부(REJECTED) — 협상이 결렬돼도
마지막에 제출한 가격으로 계약을 진행하는 운영 방침을 시스템에서 그대로 처리하기 위함이다.
자동 낙찰(close_and_decide)과 결과 컬럼은 같되, 알림에 manual 플래그로 '직접 낙찰'임을 남긴다.
권한: 본인이 생성한 견적만. 단 최고관리자(OWNER)는 회사 내 남의 견적도 낙찰할 수 있다."""
res = Res_Quotation()
@@ -187,23 +200,20 @@ class ClosingMixin:
res.msg = "개찰(낙찰자 미정) 상태의 견적만 직접 낙찰할 수 있습니다."
return res
# 낙찰 후보 = 투찰한 협상완료(DONE) 세션. close_and_decide 와 같은 조회(list_sessions_status,
# 공급사 삭제돼도 포함되는 outerjoin)를 써서 자동낙찰과 후보 집합을 일치시킨다.
# 낙찰 후보 = 가격을 써낸 세션. close_and_decide 와 같은 조회(list_sessions_status,
# 공급사 삭제돼도 포함되는 outerjoin)를 쓴다.
err_type, rows = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.list_sessions_status(s, qt_uuid),
)
rows = rows if err_type == ErrorType.SUCCESS else []
winner = next(
(r for r in rows
if r.status == SessionStatus.DONE.value and r.bid_price is not None and r.supplier_id == sp_uuid),
None,
)
winner = next((r for r in rows if r.supplier_id == sp_uuid and _award_price(r) is not None), None)
if winner is None:
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
res.msg = "선택한 협력사는 이 견적의 낙찰 후보(투찰한 협상완료 협력사)가 아닙니다."
res.msg = "선택한 협력사는 이 견적의 낙찰 후보(가격을 제출한 협력사)가 아닙니다."
return res
winner_price = _award_price(winner)
# [동시 직접낙찰 가드] 개찰→낙찰 원자 선점. 실제로 전이한 호출자만 통과(재클릭·경합 방어).
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
@@ -219,7 +229,7 @@ class ClosingMixin:
await create_notification(
original.user_id, NotificationType.SUCCESS,
{"qt_name": original.name, "qt_number": original.number,
"winner_name": winner.name, "winner_price": winner.bid_price, "manual": True},
"winner_name": winner.name, "winner_price": winner_price, "manual": True},
ref_qt_id=qt_uuid,
)
return await self.get_quotation(qt_id, company_id)
@@ -95,12 +95,12 @@ class InvitesMixin:
async def _send_invites(self, quotation, targets: list, res: Res_NotifySessions) -> list:
"""targets [(session, supplier_name, email)] 에 초청 메일 발송. res.sent/failed 를 채우고
성공한 session_id 목록을 반환. ACS/SMTP 미설정이면 첫 발송에서 중단(EMAIL_NOT_CONFIGURED)."""
# 회사 브랜딩(초청 메일 헤더) 한 번 조회 — 견적당 동일.
settings = await DB_SESSION_MNG.execute_lambda(
# 회사명·브랜딩(메일 헤더·색·로고·문구) 한 번 조회 — 견적당 동일. 회사명은 헤더 기본값.
company_name, settings = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(), DBWRType.DB_READ.value,
lambda s: self.quotation_crud.get_company_settings(s, quotation.user_id),
lambda s: self.quotation_crud.get_company_brand(s, quotation.user_id),
)
email_header = (settings.get("branding") or {}).get("email_header")
branding = settings.get("branding") or {}
sent_ids = []
for sess, sp_name, email in targets:
subject, html, text = build_invite_email(
@@ -109,7 +109,8 @@ class InvitesMixin:
qt_number=quotation.number,
end_time=quotation.end_time,
chat_url=self._session_chat_url(sess.session_id),
email_header=email_header,
company_name=company_name,
branding=branding,
)
try:
await send_email(email, subject, html, text)
@@ -180,7 +180,7 @@ class PricingMixin:
anchors[(iid, sid)] = (value, ap)
return anchors
async def get_target_breakdown(self, session_id: str, company_id=None) -> Res_TargetBreakdown:
async def get_target_breakdown(self, session_id: str, company_id=None, user_id=None, role=None) -> Res_TargetBreakdown:
"""목표가 모달의 산정내역 응답.
저장된 목표가·앵커링가는 그대로 내려주고, 후보 목록은 _candidates 로 다시 계산한다.
@@ -195,7 +195,7 @@ class PricingMixin:
res.result.SetResult(err_type if err_type != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
return res
sess = got[0]
err_type, quotation = await self._fetch(sess.quotation_id, company_id)
err_type, quotation = await self._fetch(sess.quotation_id, company_id, user_id, role)
if err_type != ErrorType.SUCCESS or quotation is None:
res.result.SetResult(err_type if err_type != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
return res
+50 -14
View File
@@ -23,9 +23,11 @@ from router.v1.quotation.protocol import (
class QueriesMixin:
async def _fetch(self, qt_id: uuid.UUID, company_id=None):
async def _fetch(self, qt_id: uuid.UUID, company_id=None, user_id=None, role=None):
"""견적 단건 조회. (ErrorType, quotation|None) 반환.
company_id 가 주어지면 회사 스코프(작성자 회사) 가드 — 남의 회사 견적은 NOT_FOUND. 내부/스케줄러 호출은 None."""
company_id 가 주어지면 회사 스코프(작성자 회사) 가드 — 남의 회사 견적은 NOT_FOUND. 내부/스케줄러 호출은 None.
user_id 가 주어지면 조회 게이팅 — 일반(USER)은 본인 견적만, 남의 견적은 존재를 숨긴다(NOT_FOUND).
변경 액션(삭제·마감 등)은 안내 문구가 필요해 user_id 없이 부르고 각자 ACCOUNT_FORBIDDEN 게이트를 탄다."""
err_type, quotation = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(),
DBWRType.DB_READ.value,
@@ -33,6 +35,8 @@ class QueriesMixin:
)
if err_type != ErrorType.SUCCESS or quotation is None:
return ErrorType.QUOTATION_NOT_FOUND, None
if user_id is not None and not is_owner_or_admin(quotation.user_id, user_id, role):
return ErrorType.QUOTATION_NOT_FOUND, None
return ErrorType.SUCCESS, quotation
async def list_quotations(self, company_id, owner, search, status, type_, start_from, start_to, pg: PageParams) -> Res_QuotationList:
@@ -90,9 +94,9 @@ class QueriesMixin:
res.total = total
return res
async def get_quotation(self, qt_id: str, company_id=None) -> Res_Quotation:
async def get_quotation(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_Quotation:
res = Res_Quotation()
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id)
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -121,9 +125,9 @@ class QueriesMixin:
res.result.SetResult(err_type)
return res
async def get_status(self, qt_id: str, company_id=None) -> Res_QuotationStatus:
async def get_status(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationStatus:
res = Res_QuotationStatus()
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id)
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -132,9 +136,9 @@ class QueriesMixin:
res.message = "ok"
return res
async def get_result(self, qt_id: str, company_id=None) -> Res_QuotationResult:
async def get_result(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationResult:
res = Res_QuotationResult()
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id)
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -147,10 +151,10 @@ class QueriesMixin:
res.result_count = 0
return res
async def list_sessions(self, qt_id: str, company_id=None) -> Res_QuotationSessions:
async def list_sessions(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationSessions:
res = Res_QuotationSessions()
qt_uuid = uuid.UUID(qt_id)
err_type, quotation = await self._fetch(qt_uuid, company_id)
err_type, quotation = await self._fetch(qt_uuid, company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -193,7 +197,7 @@ class QueriesMixin:
res.total = len(res.sessions)
return res
async def list_chats(self, session_id: str, company_id=None) -> Res_SessionChat:
async def list_chats(self, session_id: str, company_id=None, user_id=None, role=None) -> Res_SessionChat:
res = Res_SessionChat()
sess_uuid = uuid.UUID(session_id)
res.session_id = sess_uuid
@@ -208,7 +212,7 @@ class QueriesMixin:
if g_err != ErrorType.SUCCESS or got is None:
res.result.SetResult(g_err if g_err != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
return res
guard_err, _ = await self._fetch(got[0].quotation_id, company_id)
guard_err, _ = await self._fetch(got[0].quotation_id, company_id, user_id, role)
if guard_err != ErrorType.SUCCESS:
res.result.SetResult(guard_err)
return res
@@ -242,10 +246,10 @@ class QueriesMixin:
]
return res
async def list_cards(self, qt_id: str, company_id=None) -> Res_QuotationCards:
async def list_cards(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationCards:
res = Res_QuotationCards()
qt_uuid = uuid.UUID(qt_id)
err_type, quotation = await self._fetch(qt_uuid, company_id)
err_type, quotation = await self._fetch(qt_uuid, company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -280,5 +284,37 @@ class QueriesMixin:
memo=memo,
)
)
# 봇은 버전 카드셋 밖에서도 카드를 고르므로(RL 런타임 미제한) 채팅의 사용 카드(chats.card_id)가
# 버전 목록에 없으면 화면·JSON 내보내기의 카드 매칭이 전부 null 이 된다 → 실사용 카드를 합쳐 내려준다.
# 부가 조회라 실패 시 버전 카드만으로 응답한다(목록의 참여수 집계와 같은 best-effort 패턴).
used_err, used_rows = await DB_SESSION_MNG.execute_lambda(
chats.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.list_used_cards(s, qt_uuid),
)
if used_err == ErrorType.SUCCESS:
seen = {c.session_card_id for c in cards}
for chat, card_pk, number, name, script, edit, condition, memo in used_rows:
# card_pk 미해석(카드 삭제 등)이면 건너뛴다 — 매칭할 카탈로그 정보가 없다.
if card_pk is None or card_pk in seen:
continue
seen.add(card_pk)
is_wild = chat.card_type == 2
cards.append(
QuotationCardData(
session_card_id=card_pk,
qt_id=quotation.qt_id,
nego_card_id=None if is_wild else card_pk,
wild_card_id=card_pk if is_wild else None,
type=chat.card_type,
number=number,
name=name,
script=script,
edit_script=edit,
condition=condition,
memo=memo,
)
)
res.cards = cards
return res
@@ -0,0 +1,74 @@
"""협상 초청 메일 미리보기(/v1/company/settings/email-preview) 테스트 — 회사 CI 슬롯 렌더 확인.
- 실제 발송(services/quotation/invites.py)과 같은 build_invite_email 을 타므로 미리보기 검증 = 발송물 검증.
- 헤더는 회사 CI(logo_url·service_name)를 그대로 쓰고 색은 솔루션 고정 — 메일 전용 설정은 인사 문구뿐.
- 색은 hex 만 통과한다(이상값이 style 을 깨거나 CSS 주입되는 것 방지).
"""
PREVIEW_URL = "/v1/company/settings/email-preview"
async def test_preview_requires_login(client):
"""검증: 토큰 없이 미리보기 호출.
기대결과: HTTP 401/403 으로 거부(로그인 필수)."""
r = await client.post(PREVIEW_URL, json={"branding": {}})
assert r.status_code in (401, 403)
async def test_preview_default_branding(client, auth_headers):
"""검증: branding 비운 채 미리보기 호출.
기대결과: 헤더는 회사명 텍스트(테스트사, NEGODATA 아님)·기본색(#3182f6)·기본 인사 문구로 렌더되고 제목이 채워진다."""
h = await auth_headers("previewer1")
r = await client.post(PREVIEW_URL, json={"branding": {}}, headers=h)
assert r.status_code == 200
body = r.json()
assert "협상 참여 요청" in body["subject"]
html = body["html"]
assert "테스트사" in html # conftest company_id 픽스처의 회사명
assert "NEGODATA" not in html
assert "#3182f6" in html
assert "아래 견적 건의 협상에 참여해 주세요." in html
assert "negotium B2B 구매협상 솔루션" in html # 발주사 CI 아래 솔루션 태그라인(고정)
async def test_preview_ci_branding(client, auth_headers):
"""검증: 회사 CI(서비스명·로고)와 인사 문구를 채워 미리보기 호출(브랜드 색을 넣어도 무시).
기대결과: 헤더는 로고 이미지(서비스명은 alt), 색은 회사 값과 무관하게 솔루션 기본색으로 렌더."""
h = await auth_headers("previewer2")
branding = {
"service_name": "아이좋아네고",
"logo_url": "https://cdn.example.com/ci.png",
"primary_color": "#f551a0", # 제거된 기능 — 값을 보내도 반영되지 않아야 한다
"email_greeting": "협상에 초대합니다.",
}
r = await client.post(PREVIEW_URL, json={"branding": branding}, headers=h)
assert r.status_code == 200
html = r.json()["html"]
assert '<img src="https://cdn.example.com/ci.png"' in html
assert 'alt="아이좋아네고"' in html
assert "#f551a0" not in html
assert "#3182f6" in html
assert "협상에 초대합니다." in html
async def test_preview_service_name_without_logo(client, auth_headers):
"""검증: 로고 없이 서비스명만 채워 미리보기 호출.
기대결과: 헤더는 서비스명 텍스트로 렌더되고 img 태그는 없다."""
h = await auth_headers("previewer3")
r = await client.post(PREVIEW_URL, json={"branding": {"service_name": "IMK 구매협상"}}, headers=h)
assert r.status_code == 200
html = r.json()["html"]
assert "IMK 구매협상" in html
assert "<img" not in html
async def test_preview_bad_color_falls_back(client, auth_headers):
"""검증: hex 가 아닌 primary_color(CSS 주입 꼴)로 미리보기 호출.
기대결과: 입력값은 HTML 에 실리지 않고 기본색(#3182f6)으로 렌더된다."""
h = await auth_headers("previewer4")
bad = "red;background-image:url(https://evil)"
r = await client.post(PREVIEW_URL, json={"branding": {"primary_color": bad}}, headers=h)
assert r.status_code == 200
html = r.json()["html"]
assert bad not in html
assert "#3182f6" in html
@@ -0,0 +1,33 @@
"""LPS 몰별 확인 상태 미러링 — '없었다'와 '못 봤다'를 화면까지 나르는 계약.
by_mall 은 **가격이 있는 몰만** 담는다. 그래서 빠진 몰이 '거기엔 없더라'인지 '거기를 못 봤다'인지는
sources/partial 에만 있다. 이 값이 중간에서 빠지면 화면은 두 경우를 구분할 방법이 없다
(실제로 그래서 차단당한 몰이 '없음'으로 보였다 — lps/docs/result-states.md).
"""
from crud.lps_sync_crud import _price_history
from router.v1.item.protocol import LowestPriceEntry
def test_read_contract_includes_source_state():
"""lps_db 읽기 계약에서 이 컬럼이 빠지면 화면까지 갈 값이 사라진다."""
cols = {c.name for c in _price_history.columns}
assert {"sources", "partial"} <= cols, cols
assert "by_mall" in cols # 함께 읽어야 '가격 있는 몰'과 '확인한 몰'을 대조할 수 있다
def test_api_entry_exposes_state_with_safe_defaults():
"""이 컬럼 추가 이전 이력(값 없음)도 화면이 깨지지 않아야 한다."""
e = LowestPriceEntry()
assert e.sources is None
assert e.partial is False, "기본이 True 면 정상 결과가 '일부 확인 못함'으로 보인다"
def test_api_entry_carries_source_state():
e = LowestPriceEntry(
lp_price=9000, success_yn=True, partial=True,
sources={"naver": {"state": "matched", "count": 40},
"coupang": {"state": "blocked", "error": "차단"}},
)
assert e.partial is True
assert e.sources["coupang"]["state"] == "blocked"
@@ -0,0 +1,142 @@
"""견적 조회 게이팅 + 사용 카드 매칭 보강.
- 조회 게이팅: 일반(USER)은 본인 견적만 — 목록은 서버가 강제 필터, 상세는 남의 견적의 존재 자체를
숨긴다(QUOTATION_NOT_FOUND). OWNER 이상은 회사 전체 조회. 판정은 common.authz.is_owner_or_admin 공용.
- 사용 카드: 봇은 버전 카드셋 밖에서도 카드를 고르므로(RL 런타임 미제한) 버전 목록에 없는
실사용 카드(chats.card_id)도 /cards 응답에 합쳐 내려준다 — 협상로그 화면·JSON 내보내기의
카드 매칭 실패(card=null) 복구.
"""
import uuid
from datetime import datetime
from sqlalchemy import text
from common.enums import ChatSender, ErrorType, QuotationStatus, QuotationType, SessionStatus, UserRole
from crud.quotation_crud import QuotationCRUD
from services.quotation import QuotationService
PAST = datetime(2020, 1, 1)
# ===== 목록 — HTTP e2e: 같은 회사, 담당자 2명 =====
async def test_list_forced_to_own_for_user_role(client, auth_headers, db_engine):
"""검증: 같은 회사 담당자 A/B 가 견적을 하나씩 가진 상태에서 일반유저 B 가 목록 조회(mine 미지정).
기대결과: B 본인 견적만 내려온다 — 서버가 mine 을 강제해 A 견적은 목록에서 제외."""
ha = await auth_headers("read_user_a")
hb = await auth_headers("read_user_b")
qt_a = await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_user_a"), number="READ-A")
await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_user_b"), number="READ-B")
numbers = [q["number"] for q in (await client.get("/v1/quotation/list", headers=hb)).json()["quotations"]]
assert numbers == ["READ-B"]
# 소유자 A 본인은 당연히 자기 견적을 본다(대조군)
assert (await client.get(f"/v1/quotation/{qt_a}", headers=ha)).json()["result"]["success"] is True
async def test_list_full_company_for_owner_role(client, auth_headers, db_engine):
"""검증: 최고관리자(OWNER)가 목록 조회(mine 미지정).
기대결과: 회사 전체 — 다른 담당자들 견적까지 모두 내려온다."""
await auth_headers("read_user_c")
hadmin = await auth_headers("read_admin", role=UserRole.OWNER.value)
await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_user_c"), number="READ-C")
await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_admin"), number="READ-D")
numbers = {q["number"] for q in (await client.get("/v1/quotation/list", headers=hadmin)).json()["quotations"]}
assert numbers == {"READ-C", "READ-D"}
# ===== 상세 — HTTP e2e: 남의 견적 =====
async def test_detail_hidden_from_other_user(client, auth_headers, db_engine):
"""검증: A 의 견적 상세(/{qt_id}·/sessions·/cards)를 같은 회사 일반유저 B 가 조회.
기대결과: 모두 거부 — 존재를 숨기는 QUOTATION_NOT_FOUND(권한 코드가 아니라 미존재로 응답)."""
await auth_headers("read_owner")
hb = await auth_headers("read_other")
qt = await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_owner"), number="READ-HIDE")
for path in (f"/v1/quotation/{qt}", f"/v1/quotation/{qt}/sessions", f"/v1/quotation/{qt}/cards"):
body = (await client.get(path, headers=hb)).json()
assert body["result"]["success"] is False
assert body["result"]["code"] == ErrorType.QUOTATION_NOT_FOUND.value
async def test_detail_visible_to_owner_role(client, auth_headers, db_engine):
"""검증: A 의 견적 상세를 같은 회사 최고관리자(OWNER)가 조회.
기대결과: 성공 — 소유자가 아니어도 OWNER 는 조회 가능."""
await auth_headers("read_owner2")
hadmin = await auth_headers("read_admin2", role=UserRole.OWNER.value)
qt = await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_owner2"), number="READ-SHOW")
body = (await client.get(f"/v1/quotation/{qt}", headers=hadmin)).json()
assert body["result"]["success"] is True
assert body["quotation"]["number"] == "READ-SHOW"
# ===== 사용 카드 — 서비스 직접: 버전 밖 카드 매칭 =====
async def test_list_cards_includes_used_card_outside_version(db_engine):
"""검증: 버전 카드셋엔 없는 카드를 채팅에서 사용(chats.card_used_yn=true, card_id=카드 PK)한 견적의 카드 조회.
기대결과: 응답에 그 카드가 session_card_id=카드 PK 로 포함 — 화면·내보내기 매칭이 성립한다."""
user = uuid.uuid4()
qt = await _seed_quotation(db_engine, user_id=user, number="CARD-USED")
card = uuid.uuid4()
session = uuid.uuid4()
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO nego_cards (nego_card_id, user_id, name, number, script, usage_type) "
"VALUES (:c, :u, '실사용카드', 'NGC-X1', '멘트', 1)"),
{"c": card, "u": user},
)
await conn.execute(
text(
"INSERT INTO sessions "
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
" target_price, status, end_time) VALUES "
"(:sid, :qt, :item, :sup, 'CARD-USED', 1, :type, 0, :st, :t)"
),
{"sid": session, "qt": qt, "item": uuid.uuid4(), "sup": uuid.uuid4(),
"type": QuotationType.REQUOTE.value, "st": SessionStatus.DONE.value, "t": PAST},
)
await conn.execute(
text(
"INSERT INTO chats (chat_id, session_id, card_id, seq, sender, target_price, card_used_yn, card_type) "
"VALUES (:cid, :sid, :card, 1, :sender, 0, true, 1)"
),
{"cid": uuid.uuid4(), "sid": session, "card": card, "sender": ChatSender.BOT.value},
)
res = await QuotationService(QuotationCRUD()).list_cards(str(qt))
assert res.result.success is True
got = {str(c.session_card_id): c for c in res.cards}
assert str(card) in got
assert got[str(card)].number == "NGC-X1"
assert got[str(card)].nego_card_id == card # nego 카드로 분류(type=1)
# ===== 헬퍼 =====
async def _user_id(engine, login_id) -> uuid.UUID:
async with engine.begin() as conn:
return (await conn.execute(
text("SELECT user_id FROM users WHERE id = :i"), {"i": login_id}
)).scalar_one()
async def _seed_quotation(engine, *, user_id, number):
"""견적 1건 시드(조회 게이팅 확인용 — 상태는 무관하므로 CLOSED 고정)."""
qt_id = uuid.uuid4()
async with engine.begin() as conn:
await conn.execute(
text(
"INSERT INTO quotations "
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, "
" round, iteration, start_time, end_time, deleted) VALUES "
"(:qt_id, :user_id, :qt_setting_id, :version_id, '견적', :number, :type, :status, "
" 1, 0, :t, :t, false)"
),
{
"qt_id": qt_id, "user_id": user_id, "qt_setting_id": uuid.uuid4(),
"version_id": uuid.uuid4(), "number": number, "type": QuotationType.REQUOTE.value,
"status": QuotationStatus.CLOSED.value, "t": PAST,
},
)
return qt_id
Binary file not shown.
+4
View File
@@ -3,6 +3,10 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<!-- 구글폰트 Noto Sans KR — self-host Pretendard 가 어떤 환경에서든 못 뜰 때 한글이 굴림/맑은고딕으로 떨어지지 않게 하는 안전망 -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300..900&display=swap" rel="stylesheet" />
<title>NegoData</title>
</head>
<body>
@@ -25,8 +25,10 @@ import type {
import type {
HTTPValidationError,
ReqPreviewInviteEmail,
ReqUpdateCompanySettings,
ResCompanySettings
ResCompanySettings,
ResPreviewInviteEmail
} from '.././model';
import { customFetch } from '../../mutator/custom-fetch';
@@ -191,4 +193,68 @@ export const useUpdateSettings = <TError = void | HTTPValidationError,
return useMutation(mutationOptions, queryClient);
}
/**
* @summary 협상 초청 메일 미리보기
*/
export const previewInviteEmail = (
reqPreviewInviteEmail: ReqPreviewInviteEmail,
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
) => {
return customFetch<ResPreviewInviteEmail>(
{url: `/v1/company/settings/email-preview`, method: 'POST',
headers: {'Content-Type': 'application/json', },
data: reqPreviewInviteEmail, signal
},
options);
}
export const getPreviewInviteEmailMutationOptions = <TError = void | HTTPValidationError,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof previewInviteEmail>>, TError,{data: ReqPreviewInviteEmail}, TContext>, request?: SecondParameter<typeof customFetch>}
): UseMutationOptions<Awaited<ReturnType<typeof previewInviteEmail>>, TError,{data: ReqPreviewInviteEmail}, TContext> => {
const mutationKey = ['previewInviteEmail'];
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof previewInviteEmail>>, {data: ReqPreviewInviteEmail}> = (props) => {
const {data} = props ?? {};
return previewInviteEmail(data,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type PreviewInviteEmailMutationResult = NonNullable<Awaited<ReturnType<typeof previewInviteEmail>>>
export type PreviewInviteEmailMutationBody = ReqPreviewInviteEmail
export type PreviewInviteEmailMutationError = void | HTTPValidationError
/**
* @summary 협상 초청 메일 미리보기
*/
export const usePreviewInviteEmail = <TError = void | HTTPValidationError,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof previewInviteEmail>>, TError,{data: ReqPreviewInviteEmail}, TContext>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof previewInviteEmail>>,
TError,
{data: ReqPreviewInviteEmail},
TContext
> => {
const mutationOptions = getPreviewInviteEmailMutationOptions(options);
return useMutation(mutationOptions, queryClient);
}
@@ -0,0 +1,217 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import {
useQuery
} from '@tanstack/react-query';
import type {
DataTag,
DefinedInitialDataOptions,
DefinedUseQueryResult,
QueryClient,
QueryFunction,
QueryKey,
UndefinedInitialDataOptions,
UseQueryOptions,
UseQueryResult
} from '@tanstack/react-query';
import type {
ResAnchoringStatus,
ResLearningStatus
} from '.././model';
import { customFetch } from '../../mutator/custom-fetch';
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
/**
* @summary 협상카드 학습 현황
*/
export const getLearningStatus = (
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
) => {
return customFetch<ResLearningStatus>(
{url: `/v1/learning/cards`, method: 'GET', signal
},
options);
}
export const getGetLearningStatusQueryKey = () => {
return [
`/v1/learning/cards`
] as const;
}
export const getGetLearningStatusQueryOptions = <TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetLearningStatusQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getLearningStatus>>> = ({ signal }) => getLearningStatus(requestOptions, signal);
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetLearningStatusQueryResult = NonNullable<Awaited<ReturnType<typeof getLearningStatus>>>
export type GetLearningStatusQueryError = void
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getLearningStatus>>,
TError,
Awaited<ReturnType<typeof getLearningStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getLearningStatus>>,
TError,
Awaited<ReturnType<typeof getLearningStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary 협상카드 학습 현황
*/
export function useGetLearningStatus<TData = Awaited<ReturnType<typeof getLearningStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getLearningStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetLearningStatusQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
query.queryKey = queryOptions.queryKey ;
return query;
}
/**
* @summary 앵커링 현황·조정 이력
*/
export const getAnchoringStatus = (
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
) => {
return customFetch<ResAnchoringStatus>(
{url: `/v1/learning/anchoring`, method: 'GET', signal
},
options);
}
export const getGetAnchoringStatusQueryKey = () => {
return [
`/v1/learning/anchoring`
] as const;
}
export const getGetAnchoringStatusQueryOptions = <TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetAnchoringStatusQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getAnchoringStatus>>> = ({ signal }) => getAnchoringStatus(requestOptions, signal);
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetAnchoringStatusQueryResult = NonNullable<Awaited<ReturnType<typeof getAnchoringStatus>>>
export type GetAnchoringStatusQueryError = void
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getAnchoringStatus>>,
TError,
Awaited<ReturnType<typeof getAnchoringStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getAnchoringStatus>>,
TError,
Awaited<ReturnType<typeof getAnchoringStatus>>
> , 'initialData'
>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary 앵커링 현황·조정 이력
*/
export function useGetAnchoringStatus<TData = Awaited<ReturnType<typeof getAnchoringStatus>>, TError = void>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getAnchoringStatus>>, TError, TData>>, request?: SecondParameter<typeof customFetch>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetAnchoringStatusQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
query.queryKey = queryOptions.queryKey ;
return query;
}
@@ -0,0 +1,16 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { AnchoringCellLastAdjustedAt } from './anchoringCellLastAdjustedAt';
export interface AnchoringCell {
supplier_type?: number;
supplier_type_label?: string;
price_range_index?: number;
price_range_label?: string;
anchoring_value?: number;
last_adjusted_at?: AnchoringCellLastAdjustedAt;
}
@@ -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 AnchoringCellLastAdjustedAt = string | null;
@@ -0,0 +1,19 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { AnchoringHistoryRowCreatedAt } from './anchoringHistoryRowCreatedAt';
export interface AnchoringHistoryRow {
supplier_type_label?: string;
price_range_index?: number;
price_range_label?: string;
value_before?: number;
value_after?: number;
sample_count?: number;
success_count?: number;
success_rate?: number;
created_at?: AnchoringHistoryRowCreatedAt;
}
@@ -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 AnchoringHistoryRowCreatedAt = string | null;
@@ -0,0 +1,21 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { CardUsageRowName } from './cardUsageRowName';
import type { CardUsageRowCardId } from './cardUsageRowCardId';
import type { CardUsageRowLastUsedAt } from './cardUsageRowLastUsedAt';
export interface CardUsageRow {
number: string;
name?: CardUsageRowName;
card_id?: CardUsageRowCardId;
type?: string;
used_sessions?: number;
uses?: number;
share?: number;
avg_turn?: number;
last_used_at?: CardUsageRowLastUsedAt;
}
@@ -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 CardUsageRowCardId = 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 CardUsageRowLastUsedAt = 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 CardUsageRowName = string | null;
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more