Compare commits
233 Commits
main
...
feature/an
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aed0c314b7 | ||
|
|
2ad4ad05f3 | ||
|
|
0b81999cb4 | ||
|
|
2ca35cdc82 | ||
|
|
c9f89cb9b0 | ||
|
|
591af31da9 | ||
|
|
93c643cb8e | ||
|
|
94dea2ab3a | ||
|
|
d901c67125 | ||
|
|
80f7f0ac80 | ||
|
|
4944669470 | ||
|
|
2cc9ec6bb1 | ||
|
|
58408c9f5c | ||
|
|
17a29f05b8 | ||
|
|
98d370104b | ||
|
|
9531b74d0e | ||
|
|
e254c5c23d | ||
|
|
4c033b0584 | ||
|
|
4a529fc891 | ||
|
|
9f10f8fdbb | ||
|
|
1deba9e631 | ||
|
|
e6f4d5b1e7 | ||
|
|
7b71ea0179 | ||
|
|
849ce4c3c0 | ||
|
|
80b3919ac9 | ||
|
|
91f36273e9 | ||
|
|
f46071132c | ||
|
|
88a23c26c1 | ||
|
|
6db31785fa | ||
|
|
04bf7a8535 | ||
|
|
688bdb40f2 | ||
|
|
83ecf88bd4 | ||
|
|
e470deaefc | ||
|
|
f92abf94c8 | ||
|
|
2ef418ed7c | ||
|
|
0bcae4ec72 | ||
|
|
90f88450be | ||
|
|
7e7d06f32e | ||
|
|
03481dadae | ||
|
|
e1711d9176 | ||
|
|
5d7a8fc3f4 | ||
|
|
be1e6c2bb7 | ||
|
|
3631da2953 | ||
|
|
3507d17dc5 | ||
|
|
90cb91d644 | ||
|
|
aef867645e | ||
|
|
4614fc4c0d | ||
|
|
a7bcf46aaa | ||
|
|
e82f4be4af | ||
|
|
eda0429a85 | ||
|
|
71d1916efb | ||
|
|
c71c9ad678 | ||
|
|
91f8dea5b4 | ||
|
|
d6cf4c2cc1 | ||
|
|
09948c234f | ||
|
|
a23e4bad43 | ||
|
|
1088720081 | ||
|
|
497aeee75f | ||
|
|
0ae4ae66f0 | ||
|
|
232a77006a | ||
|
|
20fc528c2b | ||
|
|
0f69b50c49 | ||
|
|
dc2a992c12 | ||
|
|
21c8124811 | ||
|
|
33c6cd2d5c | ||
|
|
e5744e4f0f | ||
|
|
1720c108b5 | ||
|
|
d842c776c9 | ||
|
|
c1fae04344 | ||
|
|
b6d0fadb3c | ||
|
|
ee300f80ca | ||
|
|
846883cbfa | ||
|
|
29597d55fa | ||
|
|
442815b65e | ||
|
|
a672c7a2a0 | ||
|
|
f48e657e12 | ||
|
|
268f5bce8f | ||
|
|
ad58cde952 | ||
|
|
760aea6f89 | ||
|
|
be95f8b3d1 | ||
|
|
5519f5ae62 | ||
|
|
4b2d934839 | ||
|
|
06c975ce34 | ||
|
|
ad0b55ee2d | ||
|
|
2d09f139ca | ||
|
|
1829c3efa7 | ||
|
|
241e65aaf1 | ||
|
|
ddba17ae08 | ||
|
|
055fad574d | ||
|
|
857a058691 | ||
|
|
78f6f21228 | ||
|
|
f625a08091 | ||
|
|
50455e63c7 | ||
|
|
7dda385b7f | ||
|
|
101dda2e41 | ||
|
|
19c70e42fb | ||
|
|
90d993156e | ||
|
|
ba38c05b93 | ||
|
|
c1596a6d35 | ||
|
|
e84eda928a | ||
|
|
0460085791 | ||
|
|
0d9f4c9a23 | ||
|
|
3527cc9777 | ||
|
|
636fd66f9e | ||
|
|
69b75d6724 | ||
|
|
3ce44019bf | ||
|
|
d820d13af9 | ||
|
|
771d247163 | ||
|
|
daa697fff9 | ||
|
|
8a86a120d8 | ||
|
|
513c082cc6 | ||
|
|
4968735a80 | ||
|
|
a144a091b9 | ||
|
|
ebd4669d24 | ||
|
|
c7169e6679 | ||
|
|
2eb92daf3e | ||
|
|
b4e4a44981 | ||
|
|
e33204f265 | ||
|
|
0bbc8a56f7 | ||
|
|
0b17139daa | ||
|
|
7ac3f7a8b4 | ||
|
|
cb90d4a7a6 | ||
|
|
f3b6496c91 | ||
|
|
16c3881661 | ||
|
|
59a55d6b22 | ||
|
|
4275689c29 | ||
|
|
1b33f82fd4 | ||
|
|
141b211f07 | ||
|
|
088d88878a | ||
|
|
ebf2e8a016 | ||
|
|
41428646ab | ||
|
|
4fc667b844 | ||
|
|
7928bbd55c | ||
|
|
d8aa073564 | ||
|
|
6192f635ca | ||
|
|
fc2db78816 | ||
|
|
c21aa956da | ||
|
|
8d025457c0 | ||
|
|
75448ffdc5 | ||
|
|
1054a9ed17 | ||
|
|
71c35433fc | ||
|
|
836be958db | ||
|
|
f829276431 | ||
|
|
9ff25dcbce | ||
|
|
4352a8b9a8 | ||
|
|
5a2ab044ba | ||
|
|
a89dc9b354 | ||
|
|
27da568a13 | ||
|
|
abb8ad1325 | ||
|
|
f374ca4fd1 | ||
|
|
e2d3ea032f | ||
|
|
097bc4c84f | ||
|
|
321fd0de1e | ||
|
|
77c667e1f6 | ||
|
|
1c2bfd473b | ||
|
|
6bb86f8780 | ||
|
|
e95c08ef59 | ||
|
|
27bb0b7b86 | ||
|
|
96a3df8470 | ||
|
|
e7096f7bed | ||
|
|
01f0df9294 | ||
|
|
2859dc43cc | ||
|
|
a0cbb984e5 | ||
|
|
5dd3489385 | ||
|
|
b660f324ac | ||
|
|
fa4e87b461 | ||
|
|
9ce7e884d7 | ||
|
|
5074adce20 | ||
|
|
50825c597e | ||
|
|
acf8e44aa5 | ||
|
|
546a5e7ae6 | ||
|
|
30d95c8579 | ||
|
|
51216c582f | ||
|
|
9ba2846820 | ||
|
|
0aebdaea0c | ||
|
|
467c0e91aa | ||
|
|
0676c4f466 | ||
|
|
79259d004b | ||
|
|
8aa43221d2 | ||
|
|
95fdd23817 | ||
|
|
65754f594b | ||
|
|
4a3ec38ba7 | ||
|
|
4a06e60e29 | ||
|
|
ee28f97c11 | ||
|
|
29648e3a7d | ||
|
|
4713395557 | ||
|
|
007b37e6c6 | ||
|
|
0e954ac749 | ||
|
|
887aba3a03 | ||
|
|
c154537c87 | ||
|
|
b71d511c7a | ||
|
|
ac0e1ced0e | ||
|
|
76a4280ebd | ||
|
|
c525632246 | ||
|
|
a7b3d5b7e0 | ||
|
|
695c1f707f | ||
|
|
f1e609ba9f | ||
|
|
e10b50e0c3 | ||
|
|
c279e53c3e | ||
|
|
e37659dc04 | ||
|
|
52a4f69abc | ||
|
|
1cebb02ec6 | ||
|
|
f102f6b42e | ||
|
|
16adca3646 | ||
|
|
fbe7dde4ce | ||
|
|
8c20c8b8db | ||
|
|
67e576736d | ||
|
|
4c0cd68267 | ||
|
|
68dcb919e4 | ||
|
|
6a786ff042 | ||
|
|
4c93ee038a | ||
|
|
a42af23038 | ||
|
|
180393700b | ||
|
|
21e07bcca9 | ||
|
|
95d7ebab71 | ||
|
|
c1c38c68ac | ||
|
|
fd77dcbef9 | ||
|
|
912679b137 | ||
|
|
f438f42d15 | ||
|
|
b1d5bcfc98 | ||
|
|
8b58ab0d3a | ||
|
|
c022ee21d0 | ||
|
|
d612563580 | ||
|
|
dfbc6e4761 | ||
|
|
8ee148abe4 | ||
|
|
3c9739a92e | ||
|
|
73b8c8ec88 | ||
|
|
4254a0f7a2 | ||
|
|
e12328ec17 | ||
|
|
009d133aef | ||
|
|
9019347d48 | ||
|
|
b95e14419e | ||
|
|
dd28958a59 |
7
.gitignore
vendored
@ -87,5 +87,12 @@ tmp/
|
||||
*.tmp
|
||||
.claude/
|
||||
|
||||
# Test/Debug scripts (일회성 분석용)
|
||||
backend/scripts/check_*.py
|
||||
backend/scripts/find_*.py
|
||||
backend/scripts/search_*.py
|
||||
backend/scripts/compare_*.py
|
||||
backend/scripts/analyze_*.py
|
||||
|
||||
# GUI settings (user-specific)
|
||||
gui_settings.json
|
||||
|
||||
277
backend/SOOIN_API_REVERSE_ENGINEERING.md
Normal file
@ -0,0 +1,277 @@
|
||||
# 수인약품 API 리버스 엔지니어링 문서
|
||||
|
||||
## 개요
|
||||
수인약품 웹 주문 시스템의 API 구조를 분석한 문서입니다.
|
||||
지오영 API와 같은 하이브리드 방식 (Playwright 로그인 → requests 직접 호출)으로 구현합니다.
|
||||
|
||||
## 기본 정보
|
||||
|
||||
- **Base URL**: `http://sooinpharm.co.kr`
|
||||
- **인코딩**: EUC-KR (한글 파라미터 인코딩 시 주의)
|
||||
- **거래처 코드**: `50911` (청춘약국)
|
||||
- **세션 관리**: 쿠키 기반 (ASP 세션)
|
||||
|
||||
---
|
||||
|
||||
## 1. 로그인
|
||||
|
||||
### 로그인 페이지
|
||||
- **URL**: `/Homepage/intro.asp`
|
||||
- **Method**: POST (JavaScript 함수 `chkLogin()` 호출)
|
||||
|
||||
### 필드
|
||||
| 필드명 | 설명 | 예시 |
|
||||
|--------|------|------|
|
||||
| tx_id | 아이디 | thug0bin |
|
||||
| tx_pw | 비밀번호 | @Trajet6640 |
|
||||
|
||||
### 인증 쿠키
|
||||
로그인 성공 시 ASP 세션 쿠키가 발급됨:
|
||||
- `ASPSESSIONID*` (세션 ID)
|
||||
|
||||
### 로그인 성공 확인
|
||||
- 로그인 후 페이지에 "로그아웃" 링크 존재 여부로 확인
|
||||
- 로그인 후 자동으로 `/Service/Order/Order.asp`로 리다이렉트
|
||||
|
||||
---
|
||||
|
||||
## 2. 제품 검색 API
|
||||
|
||||
### URL
|
||||
```
|
||||
GET /Service/Order/Order.asp
|
||||
```
|
||||
|
||||
### 파라미터
|
||||
| 파라미터 | 필수 | 설명 | 값 예시 |
|
||||
|----------|------|------|---------|
|
||||
| so | N | 제품분류 | 0=전체, 1=전문, 2=일반 |
|
||||
| so2 | N | 주문분류 | 0=전체, 1=다빈도, 2=관심, 3=재주문 |
|
||||
| so3 | N | 검색타입 | **1=제품명, 2=KD코드, 3=표준코드** |
|
||||
| tx_maker | N | 제조사 | 한독 |
|
||||
| tx_physic | N | 검색어 | 073100220 (KD코드) |
|
||||
| tx_ven | Y | 거래처코드 | 50911 |
|
||||
| currVenNm | Y | 약국명 | 청춘약국 (URL인코딩) |
|
||||
| sDate | N | 시작일 | 20260306 |
|
||||
| eDate | N | 종료일 | 20260306 |
|
||||
| sa | N | 정렬 | phy=제품명순, ven=제조사순 |
|
||||
| Page | N | 페이지번호 | 1 |
|
||||
| tx_StockLoc | N | 재고위치 | '00001' |
|
||||
| df | N | 기간필터 | t=3개월 |
|
||||
|
||||
### KD코드 검색 예시 URL
|
||||
```
|
||||
/Service/Order/Order.asp?so=0&so2=0&so3=2&tx_physic=073100220&tx_ven=50911&currVenNm=%EC%B2%AD%EC%B6%98%EC%95%BD%EA%B5%AD&sDate=20260306&eDate=20260306&df=t
|
||||
```
|
||||
|
||||
### 응답 (HTML)
|
||||
HTML 테이블 형식으로 반환. BeautifulSoup로 파싱 필요.
|
||||
|
||||
#### 테이블 구조
|
||||
```html
|
||||
<tr class="ln_physic">
|
||||
<td>073100220</td> <!-- KD코드 -->
|
||||
<td>한국오가논</td> <!-- 제조사 -->
|
||||
<td>
|
||||
<a href="./PhysicInfo.asp?pc=32495&...">
|
||||
(오가논)코자정 50mg(PTP)
|
||||
</a>
|
||||
</td> <!-- 제품명 (pc=내부코드) -->
|
||||
<td>30T</td> <!-- 규격 -->
|
||||
<td>보험전문</td> <!-- 구분 -->
|
||||
<td>14,220</td> <!-- 단가 -->
|
||||
<td>238</td> <!-- 재고 -->
|
||||
<td>
|
||||
<input name="qty_0"> <!-- 수량입력 -->
|
||||
<input type="hidden" name="pc_0" value="32495"> <!-- 내부코드 -->
|
||||
<input type="hidden" name="stock_0" value="238">
|
||||
<input type="hidden" name="price_0" value="14220">
|
||||
</td>
|
||||
</tr>
|
||||
```
|
||||
|
||||
#### 핵심 필드 추출
|
||||
- **KD코드**: 첫 번째 td
|
||||
- **제조사**: 두 번째 td
|
||||
- **제품명**: 세 번째 td의 a 태그 텍스트
|
||||
- **내부코드(pc)**: a 태그 href에서 `pc=xxxxx` 추출
|
||||
- **규격**: 네 번째 td
|
||||
- **단가**: 여섯 번째 td (콤마 제거 후 int)
|
||||
- **재고**: 일곱 번째 td
|
||||
|
||||
---
|
||||
|
||||
## 3. 장바구니 추가 API
|
||||
|
||||
### URL
|
||||
```
|
||||
POST /Service/Order/BagOrder.asp
|
||||
```
|
||||
|
||||
### Content-Type
|
||||
```
|
||||
application/x-www-form-urlencoded
|
||||
```
|
||||
|
||||
### 파라미터 (각 제품당)
|
||||
| 파라미터 | 설명 | 예시 |
|
||||
|----------|------|------|
|
||||
| qty_N | 수량 | 1 |
|
||||
| pc_N | 내부 제품코드 | 32495 |
|
||||
| stock_N | 현재 재고 | 238 |
|
||||
| saleqty_N | 판매수량 | 0 |
|
||||
| price_N | 단가 | 14220 |
|
||||
| soldout_N | 품절여부 | N |
|
||||
| ordunitqty_N | 주문단위수량 | 1 |
|
||||
| bidqty_N | 입찰수량 | 0 |
|
||||
| outqty_N | 출고수량 | 0 |
|
||||
| overqty_N | 초과수량 | 0 |
|
||||
| manage_N | 관리여부 | N |
|
||||
| prodno_N | 제품번호 | (빈값) |
|
||||
| termdt_N | 종료일자 | (빈값) |
|
||||
|
||||
> N은 0부터 시작하는 행 인덱스
|
||||
|
||||
### 요청 예시
|
||||
```
|
||||
qty_0=1&pc_0=32495&stock_0=238&saleqty_0=0&price_0=14220&soldout_0=N&ordunitqty_0=1&bidqty_0=0&outqty_0=0&overqty_0=0&manage_0=N&prodno_0=&termdt_0=
|
||||
```
|
||||
|
||||
### 응답
|
||||
HTML (장바구니 iframe 내용)
|
||||
|
||||
---
|
||||
|
||||
## 4. 장바구니 비우기 API
|
||||
|
||||
### URL
|
||||
```
|
||||
GET /Service/Order/BagOrder.asp?kind=del&currVenCd=50911&currMkind=&currRealVenCd=
|
||||
```
|
||||
|
||||
### 파라미터
|
||||
| 파라미터 | 설명 | 값 |
|
||||
|----------|------|-----|
|
||||
| kind | 동작 | del |
|
||||
| currVenCd | 거래처코드 | 50911 |
|
||||
| currMkind | 종류 | (빈값) |
|
||||
| currRealVenCd | 실제거래처코드 | (빈값) |
|
||||
|
||||
---
|
||||
|
||||
## 5. 장바구니 조회 API
|
||||
|
||||
### URL
|
||||
```
|
||||
GET /Service/Order/BagOrder.asp?currVenCd=50911
|
||||
```
|
||||
|
||||
### 응답 (HTML)
|
||||
```html
|
||||
<table class="tbl_list">
|
||||
<tr>
|
||||
<td>건별취소</td>
|
||||
<td>제품명</td>
|
||||
<td>수량</td>
|
||||
<td>금액</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="...">X</a></td>
|
||||
<td>(오가논)코자정 50mg(PTP)</td>
|
||||
<td>1</td>
|
||||
<td>14,220</td>
|
||||
</tr>
|
||||
</table>
|
||||
<div>
|
||||
<dt>주문품목</dt><dd>1개</dd>
|
||||
<dt>주문금액</dt><dd>14,220원</dd>
|
||||
</div>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 주문 전송 API
|
||||
|
||||
### URL (추정)
|
||||
```
|
||||
POST /Service/Order/BagOrder.asp
|
||||
```
|
||||
|
||||
### 파라미터
|
||||
| 파라미터 | 설명 |
|
||||
|----------|------|
|
||||
| kind | order (추정) |
|
||||
| memo | 주문메모 |
|
||||
| currVenCd | 거래처코드 |
|
||||
|
||||
> 실제 주문 전송은 iframe 내 버튼 클릭으로 수행됨
|
||||
> 정확한 API 파라미터는 추가 분석 필요
|
||||
|
||||
---
|
||||
|
||||
## 7. 제품 상세 정보 API
|
||||
|
||||
### URL
|
||||
```
|
||||
GET /Service/Order/PhysicInfo.asp
|
||||
```
|
||||
|
||||
### 파라미터
|
||||
| 파라미터 | 설명 | 예시 |
|
||||
|----------|------|------|
|
||||
| pc | 내부제품코드 | 32495 |
|
||||
| ln | 행번호 | 0 |
|
||||
| currVenCd | 거래처코드 | 50911 |
|
||||
| currLoc | 재고위치 | '00001' |
|
||||
|
||||
---
|
||||
|
||||
## 구현 전략
|
||||
|
||||
### 지오영 API 패턴 적용
|
||||
|
||||
1. **Playwright 로그인**
|
||||
- 초기 로그인만 Playwright 사용
|
||||
- 쿠키 획득 후 requests 세션에 복사
|
||||
- 세션 30분 유효 (재로그인 필요 시 자동 갱신)
|
||||
|
||||
2. **requests 직접 호출**
|
||||
- 검색: GET /Service/Order/Order.asp
|
||||
- 장바구니 추가: POST /Service/Order/BagOrder.asp
|
||||
- 장바구니 비우기: GET /Service/Order/BagOrder.asp?kind=del
|
||||
- 장바구니 조회: GET /Service/Order/BagOrder.asp
|
||||
|
||||
3. **HTML 파싱**
|
||||
- BeautifulSoup 사용
|
||||
- 테이블 행에서 제품 정보 추출
|
||||
- 내부코드(pc) 추출 (장바구니 추가용)
|
||||
|
||||
### 예상 성능
|
||||
- 기존 Playwright: ~30초/주문
|
||||
- requests 직접 호출: **~1초/주문**
|
||||
|
||||
---
|
||||
|
||||
## 주의사항
|
||||
|
||||
1. **EUC-KR 인코딩**
|
||||
- 한글 파라미터는 EUC-KR로 인코딩
|
||||
- `urllib.parse.quote(text.encode('euc-kr'))`
|
||||
|
||||
2. **세션 관리**
|
||||
- ASP 세션 쿠키 유지 필수
|
||||
- 장시간 미사용 시 세션 만료
|
||||
|
||||
3. **동시 접속**
|
||||
- 동일 계정 동시 접속 시 세션 충돌 가능
|
||||
|
||||
4. **재고 실시간성**
|
||||
- 검색 시점의 재고 정보
|
||||
- 주문 전 재고 재확인 권장
|
||||
|
||||
---
|
||||
|
||||
## 작성일
|
||||
- 2026-03-06
|
||||
- 리버스 엔지니어링 by Claude
|
||||
|
||||
86
backend/analyze_baekje_ledger.py
Normal file
@ -0,0 +1,86 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""백제약품 주문 원장 페이지 분석"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
async def analyze_order_ledger():
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
username = os.getenv('BAEKJE_USER_ID')
|
||||
password = os.getenv('BAEKJE_PASSWORD')
|
||||
|
||||
print(f'Username: {username}')
|
||||
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=False)
|
||||
context = await browser.new_context()
|
||||
page = await context.new_page()
|
||||
|
||||
# 로그인 페이지
|
||||
await page.goto('https://ibjp.co.kr/dist/login', timeout=15000)
|
||||
await page.wait_for_load_state('networkidle', timeout=10000)
|
||||
|
||||
# 로그인 폼 입력
|
||||
inputs = await page.locator('input[type="text"], input[type="password"]').all()
|
||||
if len(inputs) >= 2:
|
||||
await inputs[0].fill(username)
|
||||
await inputs[1].fill(password)
|
||||
|
||||
# 로그인 버튼 클릭
|
||||
buttons = await page.locator('button').all()
|
||||
for btn in buttons:
|
||||
text = await btn.text_content()
|
||||
if '로그인' in (text or ''):
|
||||
await btn.click()
|
||||
break
|
||||
|
||||
# 로그인 완료 대기
|
||||
try:
|
||||
await page.wait_for_url('**/comOrd**', timeout=15000)
|
||||
print('Login successful, redirected to comOrd')
|
||||
except Exception as e:
|
||||
print(f'URL wait failed: {e}')
|
||||
await asyncio.sleep(3)
|
||||
|
||||
print(f'Current URL: {page.url}')
|
||||
|
||||
# 주문 원장 페이지로 이동
|
||||
await page.goto('https://ibjp.co.kr/dist/ordLedger', timeout=15000)
|
||||
await page.wait_for_load_state('networkidle', timeout=15000)
|
||||
|
||||
print(f'Order Ledger URL: {page.url}')
|
||||
|
||||
# 페이지 HTML 저장
|
||||
html = await page.content()
|
||||
with open('ordLedger_page.html', 'w', encoding='utf-8') as f:
|
||||
f.write(html)
|
||||
print('Page HTML saved to ordLedger_page.html')
|
||||
|
||||
# 스크린샷 저장
|
||||
await page.screenshot(path='ordLedger_screenshot.png', full_page=True)
|
||||
print('Screenshot saved')
|
||||
|
||||
# 테이블 데이터 분석
|
||||
tables = await page.locator('table').all()
|
||||
print(f'Found {len(tables)} tables')
|
||||
|
||||
for i, table in enumerate(tables):
|
||||
headers = await table.locator('th').all()
|
||||
header_texts = [await h.text_content() for h in headers]
|
||||
print(f'Table {i} headers: {header_texts}')
|
||||
|
||||
# 페이지 텍스트 출력 (분석용)
|
||||
body_text = await page.locator('body').text_content()
|
||||
print('\n=== Page Text Preview ===')
|
||||
print(body_text[:3000] if body_text else 'No text')
|
||||
|
||||
await asyncio.sleep(30) # 페이지 확인 시간
|
||||
await browser.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(analyze_order_ledger())
|
||||
16
backend/analyze_bag.py
Normal file
@ -0,0 +1,16 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys; sys.path.insert(0, '.'); import wholesale_path
|
||||
from wholesale import SooinSession
|
||||
|
||||
s = SooinSession()
|
||||
s.login()
|
||||
|
||||
# Bag.asp HTML 가져오기
|
||||
resp = s.session.get(f'{s.BAG_VIEW_URL}?currVenCd={s.vendor_code}', timeout=15)
|
||||
|
||||
# 파일로 저장
|
||||
with open('bag_page.html', 'w', encoding='utf-8') as f:
|
||||
f.write(resp.text)
|
||||
|
||||
print('bag_page.html 저장됨')
|
||||
print(f'응답 길이: {len(resp.text)}')
|
||||
77
backend/analyze_geoyoung.py
Normal file
@ -0,0 +1,77 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""지오영 API 엔드포인트 분석 - 간단 버전"""
|
||||
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
async def analyze():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
# 모든 요청 로깅
|
||||
all_requests = []
|
||||
|
||||
def log_request(request):
|
||||
all_requests.append({
|
||||
'url': request.url,
|
||||
'method': request.method,
|
||||
'data': request.post_data
|
||||
})
|
||||
|
||||
page.on('request', log_request)
|
||||
|
||||
# 로그인
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
# 메인 페이지 HTML 분석
|
||||
await page.goto('https://gwn.geoweb.kr/Home/Index')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
# JavaScript에서 API 엔드포인트 찾기
|
||||
js_content = await page.content()
|
||||
|
||||
await browser.close()
|
||||
|
||||
# POST 요청만 필터
|
||||
print("="*60)
|
||||
print("POST 요청들:")
|
||||
print("="*60)
|
||||
for r in all_requests:
|
||||
if r['method'] == 'POST':
|
||||
print(f"URL: {r['url']}")
|
||||
if r['data']:
|
||||
print(f"Data: {r['data'][:300]}")
|
||||
print()
|
||||
|
||||
# HTML에서 API 힌트 찾기
|
||||
print("="*60)
|
||||
print("HTML에서 발견된 API 관련 패턴:")
|
||||
print("="*60)
|
||||
|
||||
import re
|
||||
# ajax, fetch, url 패턴 찾기
|
||||
patterns = [
|
||||
r'url:\s*[\'"]([^"\']+)[\'"]',
|
||||
r'action=[\'"]([^"\']+)[\'"]',
|
||||
r'\.post\([\'"]([^"\']+)[\'"]',
|
||||
r'\.get\([\'"]([^"\']+)[\'"]',
|
||||
r'fetch\([\'"]([^"\']+)[\'"]',
|
||||
]
|
||||
|
||||
found_urls = set()
|
||||
for pattern in patterns:
|
||||
matches = re.findall(pattern, js_content)
|
||||
for m in matches:
|
||||
if 'Order' in m or 'Cart' in m or 'Add' in m or 'Product' in m:
|
||||
found_urls.add(m)
|
||||
|
||||
for url in sorted(found_urls):
|
||||
print(url)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(analyze())
|
||||
6895
backend/app.py
447
backend/baekje_api.py
Normal file
@ -0,0 +1,447 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
백제약품 도매상 API - Flask Blueprint
|
||||
|
||||
핵심 로직은 wholesale 패키지에서 가져옴
|
||||
이 파일은 Flask 웹 API 연동만 담당
|
||||
"""
|
||||
|
||||
import time
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request as flask_request
|
||||
|
||||
# wholesale 패키지 경로 설정
|
||||
import wholesale_path
|
||||
|
||||
# wholesale 패키지에서 핵심 클래스 가져오기
|
||||
from wholesale import BaekjeSession
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Blueprint 생성
|
||||
baekje_bp = Blueprint('baekje', __name__, url_prefix='/api/baekje')
|
||||
|
||||
|
||||
# ========== 세션 관리 ==========
|
||||
|
||||
_baekje_session = None
|
||||
_init_started = False
|
||||
|
||||
def get_baekje_session():
|
||||
global _baekje_session
|
||||
if _baekje_session is None:
|
||||
_baekje_session = BaekjeSession()
|
||||
return _baekje_session
|
||||
|
||||
|
||||
def init_baekje_session():
|
||||
"""앱 시작 시 백그라운드에서 로그인 시작"""
|
||||
global _init_started
|
||||
if _init_started:
|
||||
return
|
||||
_init_started = True
|
||||
|
||||
session = get_baekje_session()
|
||||
|
||||
# 저장된 토큰이 있으면 즉시 사용 가능
|
||||
if session._logged_in:
|
||||
logger.info(f"백제약품: 저장된 토큰 사용 중")
|
||||
return
|
||||
|
||||
# 백그라운드 로그인 시작
|
||||
session.start_background_login()
|
||||
logger.info(f"백제약품: 백그라운드 로그인 시작됨")
|
||||
|
||||
|
||||
# 모듈 로드 시 자동 시작
|
||||
try:
|
||||
init_baekje_session()
|
||||
except Exception as e:
|
||||
logger.warning(f"백제약품 초기화 오류: {e}")
|
||||
|
||||
|
||||
def search_baekje_stock(keyword: str):
|
||||
"""백제약품 재고 검색"""
|
||||
try:
|
||||
session = get_baekje_session()
|
||||
result = session.search_products(keyword)
|
||||
|
||||
if result.get('success'):
|
||||
return {
|
||||
'success': True,
|
||||
'keyword': keyword,
|
||||
'count': result['total'],
|
||||
'items': result['items']
|
||||
}
|
||||
else:
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"백제약품 검색 오류: {e}")
|
||||
return {'success': False, 'error': 'SEARCH_ERROR', 'message': str(e)}
|
||||
|
||||
|
||||
# ========== Flask API Routes ==========
|
||||
|
||||
@baekje_bp.route('/stock', methods=['GET'])
|
||||
def api_baekje_stock():
|
||||
"""
|
||||
백제약품 재고 조회 API
|
||||
|
||||
GET /api/baekje/stock?kd_code=672300240
|
||||
GET /api/baekje/stock?keyword=타이레놀
|
||||
"""
|
||||
kd_code = flask_request.args.get('kd_code', '').strip()
|
||||
keyword = flask_request.args.get('keyword', '').strip()
|
||||
|
||||
search_term = kd_code or keyword
|
||||
|
||||
if not search_term:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'kd_code 또는 keyword 파라미터가 필요합니다'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
result = search_baekje_stock(search_term)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"백제약품 API 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@baekje_bp.route('/session-status', methods=['GET'])
|
||||
def api_session_status():
|
||||
"""세션 상태 확인"""
|
||||
session = get_baekje_session()
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'wholesaler': 'baekje',
|
||||
'name': '백제약품',
|
||||
'logged_in': session._logged_in,
|
||||
'last_login': session._last_login,
|
||||
'session_timeout': session.SESSION_TIMEOUT
|
||||
})
|
||||
|
||||
|
||||
@baekje_bp.route('/login', methods=['POST'])
|
||||
def api_login():
|
||||
"""수동 로그인"""
|
||||
session = get_baekje_session()
|
||||
success = session.login()
|
||||
return jsonify({
|
||||
'success': success,
|
||||
'message': '로그인 성공' if success else '로그인 실패'
|
||||
})
|
||||
|
||||
|
||||
@baekje_bp.route('/cart', methods=['GET'])
|
||||
def api_get_cart():
|
||||
"""장바구니 조회"""
|
||||
session = get_baekje_session()
|
||||
result = session.get_cart()
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@baekje_bp.route('/cart', methods=['POST'])
|
||||
def api_add_to_cart():
|
||||
"""
|
||||
장바구니 추가
|
||||
|
||||
POST /api/baekje/cart
|
||||
{
|
||||
"product_code": "672300240",
|
||||
"quantity": 2
|
||||
}
|
||||
"""
|
||||
data = flask_request.get_json() or {}
|
||||
product_code = data.get('product_code', '').strip()
|
||||
quantity = int(data.get('quantity', 1))
|
||||
|
||||
if not product_code:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'product_code 필요'
|
||||
}), 400
|
||||
|
||||
session = get_baekje_session()
|
||||
result = session.add_to_cart(product_code, quantity)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@baekje_bp.route('/order', methods=['POST'])
|
||||
def api_submit_order():
|
||||
"""
|
||||
주문 등록
|
||||
|
||||
POST /api/baekje/order
|
||||
{
|
||||
"memo": "긴급 요청"
|
||||
}
|
||||
"""
|
||||
data = flask_request.get_json() or {}
|
||||
memo = data.get('memo', '')
|
||||
|
||||
session = get_baekje_session()
|
||||
result = session.submit_order(memo)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
# ========== 프론트엔드 통합용 ==========
|
||||
|
||||
@baekje_bp.route('/search-for-order', methods=['POST'])
|
||||
def api_search_for_order():
|
||||
"""
|
||||
발주용 재고 검색 (프론트엔드 통합용)
|
||||
|
||||
POST /api/baekje/search-for-order
|
||||
{
|
||||
"kd_code": "672300240",
|
||||
"product_name": "타이레놀",
|
||||
"specification": "500T"
|
||||
}
|
||||
"""
|
||||
data = flask_request.get_json() or {}
|
||||
kd_code = data.get('kd_code', '').strip()
|
||||
product_name = data.get('product_name', '').strip()
|
||||
specification = data.get('specification', '').strip()
|
||||
|
||||
search_term = kd_code or product_name
|
||||
|
||||
if not search_term:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM'
|
||||
}), 400
|
||||
|
||||
result = search_baekje_stock(search_term)
|
||||
|
||||
if result.get('success') and specification:
|
||||
# 규격 필터링
|
||||
filtered = [
|
||||
item for item in result.get('items', [])
|
||||
if specification.lower() in item.get('spec', '').lower()
|
||||
]
|
||||
result['items'] = filtered
|
||||
result['count'] = len(filtered)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
# ========== 잔고 조회 ==========
|
||||
|
||||
@baekje_bp.route('/balance', methods=['GET'])
|
||||
def api_get_balance():
|
||||
"""
|
||||
잔고액 조회
|
||||
|
||||
GET /api/baekje/balance
|
||||
GET /api/baekje/balance?year=2026
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"balance": 14193234,
|
||||
"monthly": [
|
||||
{"month": "2026-03", "sales": 6935133, "balance": 14193234, ...},
|
||||
{"month": "2026-02", "sales": 18600692, "balance": 7258101, ...}
|
||||
]
|
||||
}
|
||||
"""
|
||||
year = flask_request.args.get('year', '').strip()
|
||||
|
||||
session = get_baekje_session()
|
||||
result = session.get_balance(year if year else None)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@baekje_bp.route('/orders/summary-by-kd', methods=['GET'])
|
||||
def api_baekje_orders_by_kd():
|
||||
"""
|
||||
백제약품 주문량 KD코드별 집계 API
|
||||
|
||||
GET /api/baekje/orders/summary-by-kd?start_date=2026-03-01&end_date=2026-03-07
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"order_count": 4,
|
||||
"by_kd_code": {
|
||||
"670400830": {
|
||||
"product_name": "레바미피드정",
|
||||
"spec": "100T",
|
||||
"boxes": 2,
|
||||
"units": 200
|
||||
}
|
||||
},
|
||||
"total_products": 15
|
||||
}
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
start_date = flask_request.args.get('start_date', today).strip()
|
||||
end_date = flask_request.args.get('end_date', today).strip()
|
||||
|
||||
def parse_spec(spec: str, product_name: str = '') -> int:
|
||||
"""
|
||||
규격에서 수량 추출 (30T → 30, 100C → 100)
|
||||
"""
|
||||
combined = f"{spec} {product_name}"
|
||||
|
||||
# D(도즈) 단위는 박스 단위로 계산 (140D → 1)
|
||||
if re.search(r'\d+\s*D\b', combined, re.IGNORECASE):
|
||||
return 1
|
||||
|
||||
# T/C/P 단위가 붙은 숫자 추출 (예: 14T, 100C, 30P)
|
||||
qty_match = re.search(r'(\d+)\s*[TCP]\b', combined, re.IGNORECASE)
|
||||
if qty_match:
|
||||
return int(qty_match.group(1))
|
||||
|
||||
# 없으면 spec의 첫 번째 숫자
|
||||
if spec:
|
||||
num_match = re.search(r'(\d+)', spec)
|
||||
if num_match:
|
||||
val = int(num_match.group(1))
|
||||
# mg, ml 같은 용량 단위면 수량 1로 처리
|
||||
if re.search(r'\d+\s*(mg|ml|g)\b', spec, re.IGNORECASE):
|
||||
return 1
|
||||
return val
|
||||
|
||||
return 1
|
||||
|
||||
try:
|
||||
session = get_baekje_session()
|
||||
|
||||
# 주문 목록 + 상세를 한 번에 조회 (include_details=True)
|
||||
# 접수 상태(확정 전)도 포함됨!
|
||||
orders_result = session.get_order_list(start_date, end_date, include_details=True)
|
||||
|
||||
if not orders_result.get('success'):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': orders_result.get('error', 'ORDERS_FETCH_FAILED'),
|
||||
'by_kd_code': {},
|
||||
'order_count': 0
|
||||
})
|
||||
|
||||
orders = orders_result.get('orders', [])
|
||||
|
||||
if not orders:
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'order_count': 0,
|
||||
'period': {'start': start_date, 'end': end_date},
|
||||
'by_kd_code': {},
|
||||
'total_products': 0,
|
||||
'pending_count': 0,
|
||||
'approved_count': 0
|
||||
})
|
||||
|
||||
# KD코드별 집계 (items가 이미 각 order에 포함됨)
|
||||
kd_summary = {}
|
||||
|
||||
for order in orders:
|
||||
for item in order.get('items', []):
|
||||
# 취소 상태 제외
|
||||
status = item.get('status', '').strip()
|
||||
if '취소' in status or '삭제' in status:
|
||||
continue
|
||||
|
||||
# 백제는 kd_code가 insurance_code(BOHUM_CD)에 있음
|
||||
kd_code = item.get('kd_code', '') or item.get('insurance_code', '')
|
||||
if not kd_code:
|
||||
continue
|
||||
|
||||
product_name = item.get('product_name', '')
|
||||
spec = item.get('spec', '')
|
||||
quantity = item.get('quantity', 0) or item.get('order_qty', 0)
|
||||
per_unit = parse_spec(spec, product_name)
|
||||
total_units = quantity * per_unit
|
||||
|
||||
if kd_code not in kd_summary:
|
||||
kd_summary[kd_code] = {
|
||||
'product_name': product_name,
|
||||
'spec': spec,
|
||||
'boxes': 0,
|
||||
'units': 0
|
||||
}
|
||||
|
||||
kd_summary[kd_code]['boxes'] += quantity
|
||||
kd_summary[kd_code]['units'] += total_units
|
||||
|
||||
pending_count = orders_result.get('pending_count', 0)
|
||||
approved_count = orders_result.get('approved_count', 0)
|
||||
|
||||
logger.info(f"백제 주문량 집계: {start_date}~{end_date}, {len(orders)}건 (접수:{pending_count}, 승인:{approved_count}), {len(kd_summary)}개 품목")
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'order_count': len(orders),
|
||||
'pending_count': pending_count, # 접수 상태 (확정 전)
|
||||
'approved_count': approved_count, # 승인 상태 (확정됨)
|
||||
'period': {'start': start_date, 'end': end_date},
|
||||
'by_kd_code': kd_summary,
|
||||
'total_products': len(kd_summary)
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"백제 주문량 집계 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e),
|
||||
'by_kd_code': {},
|
||||
'order_count': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@baekje_bp.route('/monthly-sales', methods=['GET'])
|
||||
def api_get_monthly_sales():
|
||||
"""
|
||||
월간 매출(주문) 합계 조회
|
||||
|
||||
GET /api/baekje/monthly-sales?year=2026&month=3
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"total_amount": 7305877, // 월간 매출 합계
|
||||
"total_returns": 0, // 월간 반품 합계
|
||||
"net_amount": 7305877, // 순매출 (매출 - 반품)
|
||||
"total_paid": 0, // 월간 입금 합계
|
||||
"ending_balance": 14563978, // 월말 잔액
|
||||
"prev_balance": 14565453, // 전월이월금
|
||||
"from_date": "2026-03-01",
|
||||
"to_date": "2026-03-31",
|
||||
"rotate_days": 58.4 // 회전일수
|
||||
}
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
year = flask_request.args.get('year', '').strip()
|
||||
month = flask_request.args.get('month', '').strip()
|
||||
|
||||
# 기본값: 현재 연월
|
||||
now = datetime.now()
|
||||
if not year:
|
||||
year = now.year
|
||||
else:
|
||||
year = int(year)
|
||||
|
||||
if not month:
|
||||
month = now.month
|
||||
else:
|
||||
month = int(month)
|
||||
|
||||
session = get_baekje_session()
|
||||
result = session.get_monthly_sales(year, month)
|
||||
return jsonify(result)
|
||||
150
backend/bag_page.html
Normal file
@ -0,0 +1,150 @@
|
||||
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
|
||||
<link rel="stylesheet" href="http://sooinpharm.co.kr/Common/Css/Reset.css" type="text/css" media="screen" />
|
||||
<link rel="stylesheet" href="http://sooinpharm.co.kr/Common/Css/Bag.css?v=260116" type="text/css" media="screen" />
|
||||
<link rel="stylesheet" href="http://sooinpharm.co.kr/Common/Css/jquery-ui.css" type="text/css" />
|
||||
|
||||
<title>수인약품(주) :: 장바구니</title>
|
||||
</head>
|
||||
<body oncontextmenu="return false" >
|
||||
<input type="hidden" id="domainNm" name="domainNm" value="sooinpharm.co.kr" />
|
||||
<input type="hidden" id="aggqty" value="N">
|
||||
<input type='hidden' id='hardcoding' value='sooinpharm'>
|
||||
<input type='hidden' id='bidding' value=''>
|
||||
<input type='hidden' id='gumaeKind' value='U'>
|
||||
<input type="hidden" id="min_order_qty" value=""><!--최소주문수량-->
|
||||
<input type="hidden" id="BigWideFlag" value="">
|
||||
<input type="hidden" id="DayOrdAmt" value="0">
|
||||
<input type='hidden' id='baekjestockcd' value=''>
|
||||
|
||||
|
||||
<div id="msg_order" style="margin: 0px 0 2px 0px;padding: 0px 7px 2px 0;background-position-y: 50%;position:relative;">
|
||||
<div style="padding-left: 19px;line-height:13px;min-height:37px;display:table;"><span style="display: table-cell;text-align: left;vertical-align: middle;">17시 이후 주문은 다음근무일로 주문됩니다</span></div>
|
||||
</div>
|
||||
|
||||
<h1 id="bag_title">장바구니</h1>
|
||||
<div id="bag"
|
||||
style='height:518px;'
|
||||
>
|
||||
<form name="frmBag" id="frmBag" method="post" action="./OrderEnd.asp" autocomplete=off>
|
||||
<fieldset class="info">
|
||||
<legend>주문관련 버튼 및 메모</legend>
|
||||
<ul class="btn">
|
||||
<li><a href="./BagOrder.asp?kind=del&currVenCd=50911&currMkind=&currRealVenCd=" title="장바구니 비우기" id="btn_cancel_order">장바구니 비우기</a></li>
|
||||
|
||||
<input type="hidden" name="hostuser" id="hostuser" />
|
||||
|
||||
<li><input type="image" src="http://sooinpharm.co.kr/Images/Btn/btn_order_v2.gif" alt="주문전송" title="주문전송" /></li>
|
||||
|
||||
<input type='hidden' id='btnState' value='true'>
|
||||
</ul>
|
||||
|
||||
<p class="memo">
|
||||
<label for="tx_memo" >주문전송 메모</label><input type="text" name="tx_memo" id="tx_memo" maxlength="150" class="setInput_h20" title="메모" value="" />
|
||||
</p>
|
||||
|
||||
<input type="hidden" name="pDate" id="pDate" value=""/>
|
||||
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="list">
|
||||
<legend>장바구니</legend>
|
||||
<table class="bag_list" summary="스크롤링을 위해 고정시킬 테이블 제목">
|
||||
<caption>장바구니 리스트</caption>
|
||||
<colgroup>
|
||||
|
||||
<col width="30" />
|
||||
<col width="*" />
|
||||
<col width="35" />
|
||||
<col width="77" />
|
||||
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
<th scope="col" class="title1 first">건별취소</th>
|
||||
<th scope="col" class="title2">제품명</th>
|
||||
<th scope="col" class="title3">수량</th>
|
||||
<th scope="col" class="title4">금액</th>
|
||||
|
||||
</tr>
|
||||
</thead>
|
||||
</table>
|
||||
<div id="bag_view"
|
||||
style='height:375px;'
|
||||
> <!--닫는 태그-->
|
||||
<div class="wrap_table" style="height:375px;overflow-y:scroll;overflow-x:hidden;"><!--scroll div-->
|
||||
<table class="bag_list">
|
||||
<caption>장바구니 리스트</caption>
|
||||
<colgroup>
|
||||
|
||||
<col width="30" />
|
||||
<col width="*" />
|
||||
<col width="35" />
|
||||
<col width="60" />
|
||||
|
||||
</colgroup>
|
||||
<thead style="display:none;">
|
||||
<tr>
|
||||
|
||||
<th scope="col" class="title1 first">건별취소</th>
|
||||
<th scope="col" class="title2">제품명</th>
|
||||
<th scope="col" class="title3">수량</th>
|
||||
<th scope="col" class="title4">금액</th>
|
||||
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td colspan="4">장바구니에 담긴 제품이 없습니다.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div><!--scroll-->
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
|
||||
<fieldset class="total_price">
|
||||
<legend>장바구니 총 금액</legend>
|
||||
<div class="cntPhysic">
|
||||
<dl class="orderPhy">
|
||||
<dt><span>주문품목</span></dt>
|
||||
<dd class=""><span id="cnt_order">0개</span></dd>
|
||||
</dl>
|
||||
<dl class="cancelPhy">
|
||||
<dt><span>취소품목</span></dt>
|
||||
<dd class=""><span id="cnt_cancel">0개</span></dd>
|
||||
</dl>
|
||||
</div>
|
||||
<dl class="total">
|
||||
<dt>주문금액</dt>
|
||||
<dd id="bag_totPrice" class="" data="0">
|
||||
0원
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<input type="hidden" name="chkOrderOk" id="chkOrderOk" value="Y" />
|
||||
|
||||
<input type="hidden" name="order_min_amt" id="order_min_amt" value="" />
|
||||
<input type="hidden" name="intArray" id="intArray" value="-1" />
|
||||
<input type="hidden" name="currVenCd" id="currVenCd" value="50911" />
|
||||
<input type="hidden" name="currMkind" id="currMkind" value="" />
|
||||
<input type="hidden" name="kind" value="bag_saveall" />
|
||||
<input type="hidden" name="currLoc" id="currLoc" value="" />
|
||||
<input type="hidden" name="currRealVenCd" id="currRealVenCd" value="" />
|
||||
<input type="hidden" name="ven_rotation_check" id="ven_rotation_check" value="N"/>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div><!-- //bag -->
|
||||
|
||||
<input type="hidden" name="cookStockFlag_order" id="cookStockFlag_order" value="N" />
|
||||
|
||||
<script type="text/javascript" src="http://sooinpharm.co.kr/Common/Javascript/1.7.2/jquery.min.js"></script>
|
||||
<script type="text/javascript" src="http://sooinpharm.co.kr/Common/Javascript/1.8/jquery-ui.min.js"></script>
|
||||
<script type="text/javascript" src="http://sooinpharm.co.kr/Common/Javascript/Bag.js?v=250228"></script>
|
||||
<script type="text/javascript" src="http://sooinpharm.co.kr/Common/Javascript/Common.js?v=220125"></script>
|
||||
</body>
|
||||
</html>
|
||||
79
backend/capture_geoyoung_api.py
Normal file
@ -0,0 +1,79 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""지오영 API 엔드포인트 분석"""
|
||||
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
async def capture_network():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
# 네트워크 요청 캡처
|
||||
requests_log = []
|
||||
|
||||
def log_request(request):
|
||||
if 'geoweb' in request.url:
|
||||
requests_log.append({
|
||||
'url': request.url,
|
||||
'method': request.method,
|
||||
'post_data': request.post_data
|
||||
})
|
||||
|
||||
page.on('request', log_request)
|
||||
|
||||
# 로그인
|
||||
print("로그인 중...")
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
print("로그인 완료")
|
||||
|
||||
# 메인 페이지
|
||||
await page.goto('https://gwn.geoweb.kr/Home/Index')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
# 검색
|
||||
print("검색 중...")
|
||||
search_input = await page.query_selector('input#srchText, input[name="srchText"]')
|
||||
if search_input:
|
||||
await search_input.fill('643104281')
|
||||
|
||||
# 검색 버튼
|
||||
search_btn = await page.query_selector('button:has-text("검색"), input[type="submit"]')
|
||||
if search_btn:
|
||||
await search_btn.click()
|
||||
else:
|
||||
await page.keyboard.press('Enter')
|
||||
|
||||
await page.wait_for_timeout(3000)
|
||||
|
||||
# 제품 행 클릭
|
||||
print("제품 선택 중...")
|
||||
rows = await page.query_selector_all('table tbody tr')
|
||||
if rows:
|
||||
await rows[0].click()
|
||||
await page.wait_for_timeout(2000)
|
||||
|
||||
# 담기 버튼
|
||||
print("담기 버튼 클릭...")
|
||||
add_btn = await page.query_selector('button:has-text("담기")')
|
||||
if add_btn:
|
||||
await add_btn.click()
|
||||
await page.wait_for_timeout(3000)
|
||||
|
||||
await browser.close()
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("캡처된 요청들:")
|
||||
print("="*60)
|
||||
for r in requests_log:
|
||||
if r['method'] == 'POST' or 'cart' in r['url'].lower() or 'order' in r['url'].lower():
|
||||
print(f"\n[{r['method']}] {r['url']}")
|
||||
if r['post_data']:
|
||||
print(f" Data: {r['post_data'][:200]}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(capture_network())
|
||||
82
backend/capture_order.py
Normal file
@ -0,0 +1,82 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
네트워크 캡처용 - 약사님이 직접 주문 버튼 클릭
|
||||
"""
|
||||
import sys; sys.path.insert(0, '.'); import wholesale_path
|
||||
from wholesale import SooinSession
|
||||
from playwright.sync_api import sync_playwright
|
||||
import time
|
||||
|
||||
s = SooinSession()
|
||||
print('로그인...')
|
||||
s.login()
|
||||
|
||||
# 장바구니에 코자정 담기
|
||||
print('\n코자정 검색...')
|
||||
result = s.search_products('코자정 50mg PTP')
|
||||
product = None
|
||||
for item in result.get('items', []):
|
||||
if 'PTP' in item['name']:
|
||||
product = item
|
||||
break
|
||||
|
||||
if product:
|
||||
print(f"제품: {product['name']} - {product['price']:,}원")
|
||||
s.add_to_cart(product['internal_code'], qty=1,
|
||||
price=product['price'], stock=product['stock'])
|
||||
print('장바구니에 담음!')
|
||||
else:
|
||||
print('제품 못 찾음')
|
||||
|
||||
# 장바구니 확인
|
||||
cart = s.get_cart()
|
||||
print(f"\n장바구니: {cart['total_items']}개, {cart['total_amount']:,}원")
|
||||
|
||||
print('\n' + '='*50)
|
||||
print('브라우저 열기 + 네트워크 캡처 시작')
|
||||
print('='*50)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=False) # 브라우저 보임
|
||||
context = browser.new_context()
|
||||
|
||||
# 세션 쿠키 복사
|
||||
for c in s.session.cookies:
|
||||
context.add_cookies([{
|
||||
'name': c.name,
|
||||
'value': c.value,
|
||||
'domain': c.domain or 'sooinpharm.co.kr',
|
||||
'path': c.path or '/'
|
||||
}])
|
||||
|
||||
page = context.new_page()
|
||||
|
||||
# 네트워크 요청 캡처
|
||||
def on_request(request):
|
||||
if 'BagOrder' in request.url and request.method == 'POST':
|
||||
print('\n' + '='*50)
|
||||
print('🎯 POST 요청 캡처!')
|
||||
print('='*50)
|
||||
print(f'URL: {request.url}')
|
||||
print(f'\nPOST 데이터:')
|
||||
data = request.post_data or ''
|
||||
# 파라미터별로 출력
|
||||
for param in data.split('&'):
|
||||
if '=' in param:
|
||||
key, val = param.split('=', 1)
|
||||
print(f' {key}: {val[:50]}')
|
||||
print('='*50)
|
||||
|
||||
page.on('request', on_request)
|
||||
|
||||
# 주문 페이지로 이동
|
||||
page.goto('http://sooinpharm.co.kr/Service/Order/Order.asp')
|
||||
|
||||
print('\n✅ 브라우저 준비 완료!')
|
||||
print('👆 주문전송 버튼을 클릭해주세요!')
|
||||
print('\n(Enter 누르면 브라우저 닫힘)')
|
||||
input()
|
||||
|
||||
browser.close()
|
||||
|
||||
print('\n완료!')
|
||||
79
backend/capture_order2.py
Normal file
@ -0,0 +1,79 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
네트워크 캡처 v2 - 새로고침 후에도 캡처
|
||||
"""
|
||||
import sys; sys.path.insert(0, '.'); import wholesale_path
|
||||
from wholesale import SooinSession
|
||||
from playwright.sync_api import sync_playwright
|
||||
import time
|
||||
|
||||
s = SooinSession()
|
||||
print('로그인...')
|
||||
s.login()
|
||||
|
||||
# 먼저 장바구니 비우기
|
||||
s.clear_cart()
|
||||
|
||||
# 코자정 담기
|
||||
print('코자정 검색...')
|
||||
result = s.search_products('코자정')
|
||||
product = result['items'][0] if result.get('items') else None
|
||||
|
||||
if product:
|
||||
print(f"제품: {product['name']} - {product['price']:,}원")
|
||||
s.add_to_cart(product['internal_code'], qty=1,
|
||||
price=product['price'], stock=product['stock'])
|
||||
print('장바구니에 담음!')
|
||||
|
||||
cart = s.get_cart()
|
||||
print(f"장바구니: {cart['total_items']}개")
|
||||
|
||||
print('\n브라우저 열기...')
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=False)
|
||||
context = browser.new_context()
|
||||
|
||||
# 쿠키 복사
|
||||
for c in s.session.cookies:
|
||||
context.add_cookies([{
|
||||
'name': c.name,
|
||||
'value': c.value,
|
||||
'domain': c.domain or 'sooinpharm.co.kr',
|
||||
'path': c.path or '/'
|
||||
}])
|
||||
|
||||
page = context.new_page()
|
||||
|
||||
# 모든 요청 캡처 (지속적)
|
||||
captured = []
|
||||
def capture(request):
|
||||
if 'BagOrder' in request.url and request.method == 'POST':
|
||||
data = request.post_data or ''
|
||||
captured.append(data)
|
||||
print('\n' + '='*60)
|
||||
print('🎯 POST 캡처!')
|
||||
print('='*60)
|
||||
for param in data.split('&')[:30]: # 주요 파라미터만
|
||||
if '=' in param:
|
||||
k, v = param.split('=', 1)
|
||||
if v: # 값이 있는 것만
|
||||
print(f' {k}: {v[:60]}')
|
||||
print('='*60)
|
||||
|
||||
context.on('request', capture) # context 레벨에서 캡처
|
||||
|
||||
page.goto('http://sooinpharm.co.kr/Service/Order/Order.asp')
|
||||
|
||||
print('\n✅ 준비 완료!')
|
||||
print('👆 F5로 새로고침 후 주문전송 버튼 클릭!')
|
||||
print('\n(Enter 누르면 종료)')
|
||||
input()
|
||||
|
||||
# 캡처된 데이터 파일로 저장
|
||||
if captured:
|
||||
with open('captured_post.txt', 'w', encoding='utf-8') as f:
|
||||
f.write(captured[0])
|
||||
print('\n📁 captured_post.txt 저장됨')
|
||||
|
||||
browser.close()
|
||||
32
backend/check_2024_apc.py
Normal file
@ -0,0 +1,32 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import pyodbc
|
||||
|
||||
conn_str = (
|
||||
'DRIVER={ODBC Driver 17 for SQL Server};'
|
||||
'SERVER=192.168.0.4\\PM2014;'
|
||||
'DATABASE=PM_DRUG;'
|
||||
'UID=sa;'
|
||||
'PWD=tmddls214!%(;'
|
||||
'TrustServerCertificate=yes;'
|
||||
)
|
||||
conn = pyodbc.connect(conn_str, timeout=10)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 2024년 이후 APC (9xx로 시작) 확인
|
||||
cursor.execute('''
|
||||
SELECT G.GoodsName, U.CD_CD_BARCODE
|
||||
FROM CD_GOODS G
|
||||
JOIN CD_ITEM_UNIT_MEMBER U ON G.DrugCode = U.DRUGCODE
|
||||
WHERE G.POS_BOON = '010103'
|
||||
AND G.GoodsSelCode = 'B'
|
||||
AND U.CD_CD_BARCODE LIKE '9%'
|
||||
AND LEN(U.CD_CD_BARCODE) = 13
|
||||
ORDER BY G.GoodsName
|
||||
''')
|
||||
|
||||
rows = cursor.fetchall()
|
||||
print(f'=== 2024년 이후 APC 제품: {len(rows)}건 ===')
|
||||
for row in rows:
|
||||
print(f' {row.GoodsName} | APC: {row.CD_CD_BARCODE}')
|
||||
|
||||
conn.close()
|
||||
@ -1,70 +0,0 @@
|
||||
"""
|
||||
바코드가 있는 제품 샘플 조회
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from db.dbsetup import DatabaseManager
|
||||
from sqlalchemy import text
|
||||
|
||||
def check_barcode_samples():
|
||||
"""바코드가 있는 제품 샘플 조회"""
|
||||
db_manager = DatabaseManager()
|
||||
|
||||
try:
|
||||
session = db_manager.get_session('PM_PRES')
|
||||
|
||||
# 바코드가 있는 제품 샘플 조회
|
||||
query = text("""
|
||||
SELECT TOP 10
|
||||
S.DrugCode,
|
||||
S.BARCODE,
|
||||
G.GoodsName,
|
||||
S.SL_NM_cost_a as price
|
||||
FROM SALE_SUB S
|
||||
LEFT JOIN PM_DRUG.dbo.CD_GOODS G ON S.DrugCode = G.DrugCode
|
||||
WHERE S.BARCODE IS NOT NULL AND S.BARCODE != ''
|
||||
ORDER BY S.SL_NO_order DESC
|
||||
""")
|
||||
|
||||
results = session.execute(query).fetchall()
|
||||
|
||||
print('=' * 100)
|
||||
print('바코드가 있는 제품 샘플 (최근 10개)')
|
||||
print('=' * 100)
|
||||
for r in results:
|
||||
barcode = r.BARCODE if r.BARCODE else '(없음)'
|
||||
goods_name = r.GoodsName if r.GoodsName else '(약품명 없음)'
|
||||
print(f'DrugCode: {r.DrugCode:20} | BARCODE: {barcode:20} | 제품명: {goods_name}')
|
||||
print('=' * 100)
|
||||
|
||||
# 바코드 통계
|
||||
stats_query = text("""
|
||||
SELECT
|
||||
COUNT(DISTINCT DrugCode) as total_drugs,
|
||||
COUNT(DISTINCT BARCODE) as total_barcodes,
|
||||
SUM(CASE WHEN BARCODE IS NOT NULL AND BARCODE != '' THEN 1 ELSE 0 END) as with_barcode,
|
||||
COUNT(*) as total_sales
|
||||
FROM SALE_SUB
|
||||
""")
|
||||
|
||||
stats = session.execute(stats_query).fetchone()
|
||||
|
||||
print('\n바코드 통계')
|
||||
print('=' * 100)
|
||||
print(f'전체 제품 수 (DrugCode): {stats.total_drugs:,}')
|
||||
print(f'바코드 종류 수: {stats.total_barcodes:,}')
|
||||
print(f'바코드가 있는 판매 건수: {stats.with_barcode:,}')
|
||||
print(f'전체 판매 건수: {stats.total_sales:,}')
|
||||
print(f'바코드 보유율: {stats.with_barcode / stats.total_sales * 100:.2f}%')
|
||||
print('=' * 100)
|
||||
|
||||
except Exception as e:
|
||||
print(f"오류 발생: {e}")
|
||||
finally:
|
||||
db_manager.close_all()
|
||||
|
||||
if __name__ == '__main__':
|
||||
check_barcode_samples()
|
||||
18
backend/check_chunks.py
Normal file
@ -0,0 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from utils.animal_rag import get_animal_rag
|
||||
|
||||
rag = get_animal_rag()
|
||||
rag._init_db()
|
||||
|
||||
df = rag.table.to_pandas()
|
||||
|
||||
# 개시딘 청크들 확인
|
||||
gaesidin = df[df['source'] == 'gaesidin_gel_pyoderma_fusidic_acid.md']
|
||||
print(f'개시딘 청크 수: {len(gaesidin)}개')
|
||||
print('=' * 60)
|
||||
|
||||
for i, row in gaesidin.head(5).iterrows():
|
||||
section = row['section']
|
||||
text = row['text'][:200].replace('\n', ' ')
|
||||
print(f'\n[섹션] {section}')
|
||||
print(f' → {text}...')
|
||||
25
backend/check_oridermyl.py
Normal file
@ -0,0 +1,25 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
engine = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master')
|
||||
with engine.connect() as conn:
|
||||
# 오리더밀 검색
|
||||
result = conn.execute(text("""
|
||||
SELECT apc, product_name, item_seq,
|
||||
llm_pharm->>'분류' as category,
|
||||
llm_pharm->>'간이분류' as easy_category,
|
||||
image_url1
|
||||
FROM apc
|
||||
WHERE product_name ILIKE '%오리더밀%'
|
||||
ORDER BY apc
|
||||
"""))
|
||||
|
||||
print('=== PostgreSQL 오리더밀 검색 결과 ===')
|
||||
for row in result:
|
||||
print(f'APC: {row.apc}')
|
||||
print(f' 제품명: {row.product_name}')
|
||||
print(f' item_seq: {row.item_seq}')
|
||||
print(f' 분류: {row.category}')
|
||||
print(f' 간이분류: {row.easy_category}')
|
||||
print(f' 이미지: {row.image_url1}')
|
||||
print()
|
||||
35
backend/check_real_2024_apc.py
Normal file
@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import pyodbc
|
||||
|
||||
conn_str = (
|
||||
'DRIVER={ODBC Driver 17 for SQL Server};'
|
||||
'SERVER=192.168.0.4\\PM2014;'
|
||||
'DATABASE=PM_DRUG;'
|
||||
'UID=sa;'
|
||||
'PWD=tmddls214!%(;'
|
||||
'TrustServerCertificate=yes;'
|
||||
)
|
||||
conn = pyodbc.connect(conn_str, timeout=10)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 정식 2024년 APC (92%로 시작) 확인
|
||||
cursor.execute('''
|
||||
SELECT G.GoodsName, U.CD_CD_BARCODE
|
||||
FROM CD_GOODS G
|
||||
JOIN CD_ITEM_UNIT_MEMBER U ON G.DrugCode = U.DRUGCODE
|
||||
WHERE G.POS_BOON = '010103'
|
||||
AND G.GoodsSelCode = 'B'
|
||||
AND U.CD_CD_BARCODE LIKE '92%'
|
||||
AND LEN(U.CD_CD_BARCODE) = 13
|
||||
ORDER BY G.GoodsName
|
||||
''')
|
||||
|
||||
rows = cursor.fetchall()
|
||||
print(f'=== 정식 2024년 APC (92%) 제품: {len(rows)}건 ===')
|
||||
for row in rows:
|
||||
print(f' {row.GoodsName} | APC: {row.CD_CD_BARCODE}')
|
||||
|
||||
if len(rows) == 0:
|
||||
print(' (없음 - 아직 2024년 이후 허가 제품이 등록 안 됨)')
|
||||
|
||||
conn.close()
|
||||
@ -1,83 +0,0 @@
|
||||
"""
|
||||
특정 거래의 SALE_SUB 데이터 확인
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from db.dbsetup import DatabaseManager
|
||||
from sqlalchemy import text
|
||||
|
||||
def check_sale_sub_data(transaction_id):
|
||||
"""특정 거래의 판매 상세 데이터 확인"""
|
||||
db_manager = DatabaseManager()
|
||||
|
||||
try:
|
||||
session = db_manager.get_session('PM_PRES')
|
||||
|
||||
# SALE_SUB 모든 컬럼 조회
|
||||
query = text("""
|
||||
SELECT *
|
||||
FROM SALE_SUB
|
||||
WHERE SL_NO_order = :transaction_id
|
||||
""")
|
||||
|
||||
result = session.execute(query, {'transaction_id': transaction_id}).fetchone()
|
||||
|
||||
if result:
|
||||
print("=" * 80)
|
||||
print(f"거래번호 {transaction_id}의 SALE_SUB 데이터")
|
||||
print("=" * 80)
|
||||
|
||||
# 모든 컬럼 출력
|
||||
for key in result._mapping.keys():
|
||||
value = result._mapping[key]
|
||||
print(f"{key:30} = {value}")
|
||||
|
||||
print("=" * 80)
|
||||
else:
|
||||
print(f"거래번호 {transaction_id}를 찾을 수 없습니다.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"오류 발생: {e}")
|
||||
finally:
|
||||
db_manager.close_all()
|
||||
|
||||
def check_sale_main_data(transaction_id):
|
||||
"""특정 거래의 SALE_MAIN 데이터 확인"""
|
||||
db_manager = DatabaseManager()
|
||||
|
||||
try:
|
||||
session = db_manager.get_session('PM_PRES')
|
||||
|
||||
query = text("""
|
||||
SELECT *
|
||||
FROM SALE_MAIN
|
||||
WHERE SL_NO_order = :transaction_id
|
||||
""")
|
||||
|
||||
result = session.execute(query, {'transaction_id': transaction_id}).fetchone()
|
||||
|
||||
if result:
|
||||
print("\n" + "=" * 80)
|
||||
print(f"거래번호 {transaction_id}의 SALE_MAIN 데이터")
|
||||
print("=" * 80)
|
||||
|
||||
for key in result._mapping.keys():
|
||||
value = result._mapping[key]
|
||||
print(f"{key:30} = {value}")
|
||||
|
||||
print("=" * 80)
|
||||
else:
|
||||
print(f"거래번호 {transaction_id}를 찾을 수 없습니다.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"오류 발생: {e}")
|
||||
finally:
|
||||
db_manager.close_all()
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 스크린샷의 거래번호
|
||||
check_sale_sub_data('20260123000261')
|
||||
check_sale_main_data('20260123000261')
|
||||
@ -1,54 +0,0 @@
|
||||
"""
|
||||
SALE_MAIN 테이블 컬럼 확인 스크립트
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from db.dbsetup import DatabaseManager
|
||||
from sqlalchemy import text
|
||||
|
||||
def check_sale_table_columns(table_name):
|
||||
"""테이블의 모든 컬럼 확인"""
|
||||
db_manager = DatabaseManager()
|
||||
|
||||
try:
|
||||
session = db_manager.get_session('PM_PRES')
|
||||
|
||||
# SQL Server에서 테이블 컬럼 정보 조회
|
||||
query = text(f"""
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
DATA_TYPE,
|
||||
CHARACTER_MAXIMUM_LENGTH,
|
||||
IS_NULLABLE
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_NAME = '{table_name}'
|
||||
ORDER BY ORDINAL_POSITION
|
||||
""")
|
||||
|
||||
columns = session.execute(query).fetchall()
|
||||
|
||||
print("=" * 80)
|
||||
print(f"{table_name} 테이블 컬럼 목록")
|
||||
print("=" * 80)
|
||||
|
||||
for col in columns:
|
||||
nullable = "NULL" if col.IS_NULLABLE == 'YES' else "NOT NULL"
|
||||
max_len = f"({col.CHARACTER_MAXIMUM_LENGTH})" if col.CHARACTER_MAXIMUM_LENGTH else ""
|
||||
print(f"{col.COLUMN_NAME:30} {col.DATA_TYPE}{max_len:20} {nullable}")
|
||||
|
||||
print("=" * 80)
|
||||
print(f"총 {len(columns)}개 컬럼")
|
||||
print("=" * 80)
|
||||
|
||||
except Exception as e:
|
||||
print(f"오류 발생: {e}")
|
||||
finally:
|
||||
db_manager.close_all()
|
||||
|
||||
if __name__ == '__main__':
|
||||
check_sale_table_columns('SALE_MAIN')
|
||||
print("\n\n")
|
||||
check_sale_table_columns('SALE_SUB')
|
||||
28
backend/check_tiergard.py
Normal file
@ -0,0 +1,28 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import pyodbc
|
||||
|
||||
conn_str = (
|
||||
'DRIVER={ODBC Driver 17 for SQL Server};'
|
||||
'SERVER=192.168.0.4\\PM2014;'
|
||||
'DATABASE=PM_DRUG;'
|
||||
'UID=sa;'
|
||||
'PWD=tmddls214!%(;'
|
||||
'TrustServerCertificate=yes;'
|
||||
)
|
||||
conn = pyodbc.connect(conn_str, timeout=10)
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
SELECT G.GoodsName, G.Saleprice, ISNULL(IT.IM_QT_sale_debit, 0) AS Stock
|
||||
FROM CD_GOODS G
|
||||
LEFT JOIN IM_total IT ON G.DrugCode = IT.DrugCode
|
||||
WHERE G.GoodsName LIKE '%티어가드%'
|
||||
ORDER BY G.GoodsName
|
||||
''')
|
||||
|
||||
rows = cursor.fetchall()
|
||||
print('=== 티어가드 보유 현황 ===')
|
||||
for row in rows:
|
||||
print(f'{row.GoodsName} | {row.Saleprice:,.0f}원 | 재고: {int(row.Stock)}개')
|
||||
|
||||
conn.close()
|
||||
26
backend/check_tiergard_detail.py
Normal file
@ -0,0 +1,26 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from sqlalchemy import create_engine, text
|
||||
import json
|
||||
|
||||
engine = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master')
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(text("""
|
||||
SELECT apc, product_name, llm_pharm, main_ingredient, component_name_ko
|
||||
FROM apc
|
||||
WHERE product_name ILIKE '%티어가드%60mg%'
|
||||
ORDER BY apc
|
||||
LIMIT 3
|
||||
"""))
|
||||
|
||||
print('=== 티어가드 60mg 허가사항 상세 ===')
|
||||
for row in result:
|
||||
print(f'APC: {row.apc}')
|
||||
print(f'제품명: {row.product_name}')
|
||||
print(f'main_ingredient: {row.main_ingredient}')
|
||||
print(f'component_name_ko: {row.component_name_ko}')
|
||||
if row.llm_pharm:
|
||||
llm = row.llm_pharm if isinstance(row.llm_pharm, dict) else json.loads(row.llm_pharm)
|
||||
print('llm_pharm 내용:')
|
||||
for k, v in llm.items():
|
||||
print(f' {k}: {v}')
|
||||
print()
|
||||
27
backend/check_tiergard_llm.py
Normal file
@ -0,0 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from sqlalchemy import create_engine, text
|
||||
import json
|
||||
|
||||
engine = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master')
|
||||
with engine.connect() as conn:
|
||||
# llm_pharm이 있는 티어가드 확인
|
||||
result = conn.execute(text("""
|
||||
SELECT apc, product_name, llm_pharm
|
||||
FROM apc
|
||||
WHERE product_name ILIKE '%티어가드%'
|
||||
AND llm_pharm IS NOT NULL
|
||||
AND llm_pharm::text != '{}'
|
||||
ORDER BY apc
|
||||
"""))
|
||||
|
||||
print('=== 티어가드 llm_pharm 있는 항목 ===')
|
||||
for row in result:
|
||||
print(f'APC: {row.apc}')
|
||||
print(f'제품명: {row.product_name}')
|
||||
if row.llm_pharm:
|
||||
llm = row.llm_pharm if isinstance(row.llm_pharm, dict) else json.loads(row.llm_pharm)
|
||||
print('llm_pharm:')
|
||||
for k, v in llm.items():
|
||||
if v:
|
||||
print(f' {k}: {v}')
|
||||
print()
|
||||
21
backend/check_tiergard_pg.py
Normal file
@ -0,0 +1,21 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
engine = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master')
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(text("""
|
||||
SELECT apc, product_name,
|
||||
llm_pharm->>'체중/부위' as dosage,
|
||||
llm_pharm->>'주성분' as ingredient
|
||||
FROM apc
|
||||
WHERE product_name ILIKE '%티어가드%'
|
||||
ORDER BY apc
|
||||
"""))
|
||||
|
||||
print('=== PostgreSQL 티어가드 전체 규격 ===')
|
||||
for row in result:
|
||||
print(f'APC: {row.apc}')
|
||||
print(f' 제품명: {row.product_name}')
|
||||
print(f' 용량: {row.dosage}')
|
||||
print(f' 성분: {row.ingredient}')
|
||||
print()
|
||||
54
backend/config/__init__.py
Normal file
@ -0,0 +1,54 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
도매상 설정 중앙 관리
|
||||
|
||||
사용법:
|
||||
from config import get_wholesalers, get_wholesaler
|
||||
|
||||
# 전체 도매상 목록
|
||||
wholesalers = get_wholesalers()
|
||||
|
||||
# 특정 도매상 정보
|
||||
geo = get_wholesaler('geoyoung')
|
||||
print(geo['name']) # 지오영
|
||||
print(geo['logo']) # /static/img/logo_geoyoung.ico
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
_config = None
|
||||
_config_path = Path(__file__).parent / 'wholesalers.json'
|
||||
|
||||
|
||||
def _load_config():
|
||||
global _config
|
||||
if _config is None:
|
||||
with open(_config_path, 'r', encoding='utf-8') as f:
|
||||
_config = json.load(f)
|
||||
return _config
|
||||
|
||||
|
||||
def get_wholesalers():
|
||||
"""전체 도매상 목록 반환 (순서대로)"""
|
||||
config = _load_config()
|
||||
order = config.get('order', [])
|
||||
wholesalers = config.get('wholesalers', {})
|
||||
return [wholesalers[key] for key in order if key in wholesalers]
|
||||
|
||||
|
||||
def get_wholesaler(wholesaler_id: str):
|
||||
"""특정 도매상 정보 반환"""
|
||||
config = _load_config()
|
||||
return config.get('wholesalers', {}).get(wholesaler_id)
|
||||
|
||||
|
||||
def get_all_wholesalers_dict():
|
||||
"""전체 도매상 딕셔너리 반환"""
|
||||
config = _load_config()
|
||||
return config.get('wholesalers', {})
|
||||
|
||||
|
||||
def get_config():
|
||||
"""전체 설정 반환"""
|
||||
return _load_config()
|
||||
65
backend/config/wholesalers.json
Normal file
@ -0,0 +1,65 @@
|
||||
{
|
||||
"wholesalers": {
|
||||
"geoyoung": {
|
||||
"id": "geoyoung",
|
||||
"name": "지오영",
|
||||
"shortName": "지오영",
|
||||
"icon": "🏭",
|
||||
"logo": "/static/img/logo_geoyoung.ico",
|
||||
"color": "#06b6d4",
|
||||
"gradient": "linear-gradient(135deg, #0891b2, #06b6d4)",
|
||||
"bgColor": "rgba(6, 182, 212, 0.1)",
|
||||
"api": {
|
||||
"balance": "/api/geoyoung/balance",
|
||||
"stock": "/api/geoyoung/stock",
|
||||
"order": "/api/geoyoung/order"
|
||||
},
|
||||
"env": {
|
||||
"userId": "GEOYOUNG_USER_ID",
|
||||
"password": "GEOYOUNG_PASSWORD"
|
||||
}
|
||||
},
|
||||
"sooin": {
|
||||
"id": "sooin",
|
||||
"name": "수인약품",
|
||||
"shortName": "수인",
|
||||
"icon": "💊",
|
||||
"logo": "/static/img/logo_sooin.svg",
|
||||
"color": "#a855f7",
|
||||
"gradient": "linear-gradient(135deg, #7c3aed, #a855f7)",
|
||||
"bgColor": "rgba(168, 85, 247, 0.1)",
|
||||
"api": {
|
||||
"balance": "/api/sooin/balance",
|
||||
"stock": "/api/sooin/stock",
|
||||
"order": "/api/sooin/order"
|
||||
},
|
||||
"env": {
|
||||
"userId": "SOOIN_USER_ID",
|
||||
"password": "SOOIN_PASSWORD",
|
||||
"vendorCode": "SOOIN_VENDOR_CODE"
|
||||
}
|
||||
},
|
||||
"baekje": {
|
||||
"id": "baekje",
|
||||
"name": "백제약품",
|
||||
"shortName": "백제",
|
||||
"icon": "💉",
|
||||
"logo": "/static/img/logo_baekje.svg",
|
||||
"color": "#f59e0b",
|
||||
"gradient": "linear-gradient(135deg, #d97706, #f59e0b)",
|
||||
"bgColor": "rgba(245, 158, 11, 0.1)",
|
||||
"api": {
|
||||
"balance": "/api/baekje/balance",
|
||||
"stock": "/api/baekje/stock",
|
||||
"order": "/api/baekje/order"
|
||||
},
|
||||
"env": {
|
||||
"userId": "BAEKJE_USER_ID",
|
||||
"password": "BAEKJE_PASSWORD"
|
||||
}
|
||||
}
|
||||
},
|
||||
"order": ["baekje", "geoyoung", "sooin"],
|
||||
"version": "1.0.0",
|
||||
"lastUpdated": "2026-03-06"
|
||||
}
|
||||
50
backend/create_limits_table.py
Normal file
@ -0,0 +1,50 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect('db/orders.db')
|
||||
cur = conn.cursor()
|
||||
|
||||
# wholesaler_limits 테이블 생성
|
||||
cur.execute('''
|
||||
CREATE TABLE IF NOT EXISTS wholesaler_limits (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
wholesaler_id TEXT NOT NULL UNIQUE,
|
||||
|
||||
-- 한도 설정
|
||||
monthly_limit INTEGER DEFAULT 0, -- 월 한도 (원)
|
||||
warning_threshold REAL DEFAULT 0.9, -- 경고 임계값 (90%)
|
||||
|
||||
-- 우선순위
|
||||
priority INTEGER DEFAULT 1, -- 1이 최우선
|
||||
|
||||
-- 상태
|
||||
is_active INTEGER DEFAULT 1,
|
||||
|
||||
-- 메타
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
''')
|
||||
|
||||
# 기본 데이터 삽입 (각 2000만원)
|
||||
wholesalers = [
|
||||
('geoyoung', 20000000, 0.9, 1),
|
||||
('sooin', 20000000, 0.9, 2),
|
||||
('baekje', 20000000, 0.9, 3),
|
||||
]
|
||||
|
||||
for ws_id, limit, threshold, priority in wholesalers:
|
||||
cur.execute('''
|
||||
INSERT OR REPLACE INTO wholesaler_limits
|
||||
(wholesaler_id, monthly_limit, warning_threshold, priority)
|
||||
VALUES (?, ?, ?, ?)
|
||||
''', (ws_id, limit, threshold, priority))
|
||||
|
||||
conn.commit()
|
||||
|
||||
# 확인
|
||||
cur.execute('SELECT * FROM wholesaler_limits')
|
||||
print('=== wholesaler_limits 생성 완료 ===')
|
||||
for row in cur.fetchall():
|
||||
print(row)
|
||||
|
||||
conn.close()
|
||||
47
backend/db/animal_chat_logs_schema.sql
Normal file
@ -0,0 +1,47 @@
|
||||
-- 동물약 챗봇 로그 스키마
|
||||
-- 생성일: 2026-03-08
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT,
|
||||
|
||||
-- 입력
|
||||
user_message TEXT,
|
||||
history_length INTEGER,
|
||||
|
||||
-- MSSQL (보유 동물약)
|
||||
mssql_drug_count INTEGER,
|
||||
mssql_duration_ms INTEGER,
|
||||
|
||||
-- PostgreSQL (RAG)
|
||||
pgsql_rag_count INTEGER,
|
||||
pgsql_duration_ms INTEGER,
|
||||
|
||||
-- LanceDB (벡터 검색)
|
||||
vector_results_count INTEGER,
|
||||
vector_top_scores TEXT, -- JSON: [0.92, 0.85, 0.78]
|
||||
vector_sources TEXT, -- JSON: ["file1.md#section", ...]
|
||||
vector_duration_ms INTEGER,
|
||||
|
||||
-- OpenAI
|
||||
openai_model TEXT,
|
||||
openai_prompt_tokens INTEGER,
|
||||
openai_completion_tokens INTEGER,
|
||||
openai_total_tokens INTEGER,
|
||||
openai_cost_usd REAL,
|
||||
openai_duration_ms INTEGER,
|
||||
|
||||
-- 출력
|
||||
assistant_response TEXT,
|
||||
products_mentioned TEXT, -- JSON array
|
||||
|
||||
-- 메타
|
||||
total_duration_ms INTEGER,
|
||||
error TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now', 'localtime'))
|
||||
);
|
||||
|
||||
-- 인덱스
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_created ON chat_logs(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_session ON chat_logs(session_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_error ON chat_logs(error);
|
||||
@ -2,6 +2,8 @@
|
||||
PIT3000 Database Setup
|
||||
SQLAlchemy 기반 데이터베이스 연결 및 스키마 정의
|
||||
Windows/Linux 크로스 플랫폼 지원
|
||||
|
||||
PostgreSQL 지원 추가: 건조시럽 환산계수 조회 (drysyrup 테이블)
|
||||
"""
|
||||
|
||||
from sqlalchemy import create_engine, MetaData, text
|
||||
@ -87,6 +89,9 @@ class DatabaseConfig:
|
||||
|
||||
# URL 인코딩된 드라이버
|
||||
DRIVER_ENCODED = urllib.parse.quote_plus(DRIVER)
|
||||
|
||||
# PostgreSQL 연결 정보 (건조시럽 환산계수 DB)
|
||||
POSTGRES_URL = "postgresql+psycopg2://admin:trajet6640@192.168.0.39:5432/label10"
|
||||
|
||||
# 데이터베이스별 연결 문자열 (동적 드라이버 사용)
|
||||
@classmethod
|
||||
@ -135,6 +140,10 @@ class DatabaseManager:
|
||||
# SQLite 연결 추가
|
||||
self.sqlite_conn = None
|
||||
self.sqlite_db_path = Path(__file__).parent / 'mileage.db'
|
||||
|
||||
# PostgreSQL 연결 (건조시럽 환산계수)
|
||||
self.postgres_engine = None
|
||||
self.postgres_session = None
|
||||
|
||||
def get_engine(self, database='PM_BASE'):
|
||||
"""특정 데이터베이스 엔진 반환"""
|
||||
@ -154,11 +163,46 @@ class DatabaseManager:
|
||||
return self.engines[database]
|
||||
|
||||
def get_session(self, database='PM_BASE'):
|
||||
"""특정 데이터베이스 세션 반환"""
|
||||
"""특정 데이터베이스 세션 반환 (자동 복구 포함)"""
|
||||
if database not in self.sessions:
|
||||
engine = self.get_engine(database)
|
||||
Session = sessionmaker(bind=engine)
|
||||
self.sessions[database] = Session()
|
||||
else:
|
||||
# 🔥 기존 세션 상태 체크 및 자동 복구
|
||||
session = self.sessions[database]
|
||||
try:
|
||||
# 세션이 유효한지 간단한 쿼리로 테스트
|
||||
session.execute(text("SELECT 1"))
|
||||
except Exception as e:
|
||||
error_msg = str(e).lower()
|
||||
# 연결 끊김 또는 트랜잭션 에러 감지
|
||||
if any(keyword in error_msg for keyword in [
|
||||
'invalid transaction', 'rollback', 'connection',
|
||||
'closed', 'lost', 'timeout', 'network', 'disconnect'
|
||||
]):
|
||||
print(f"[DB Manager] {database} 세션 복구 시도: {e}")
|
||||
try:
|
||||
session.rollback()
|
||||
print(f"[DB Manager] {database} 롤백 성공, 세션 재사용")
|
||||
except Exception as rollback_err:
|
||||
print(f"[DB Manager] {database} 롤백 실패, 세션 재생성: {rollback_err}")
|
||||
try:
|
||||
session.close()
|
||||
except:
|
||||
pass
|
||||
del self.sessions[database]
|
||||
# 새 세션 생성
|
||||
engine = self.get_engine(database)
|
||||
Session = sessionmaker(bind=engine)
|
||||
self.sessions[database] = Session()
|
||||
print(f"[DB Manager] {database} 새 세션 생성 완료")
|
||||
else:
|
||||
# 다른 종류의 에러면 롤백만 시도
|
||||
try:
|
||||
session.rollback()
|
||||
except:
|
||||
pass
|
||||
return self.sessions[database]
|
||||
|
||||
def rollback_session(self, database='PM_BASE'):
|
||||
@ -185,6 +229,132 @@ class DatabaseManager:
|
||||
# 새 세션 생성
|
||||
return self.get_session(database)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# PostgreSQL 연결 (건조시럽 환산계수)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
def get_postgres_engine(self):
|
||||
"""
|
||||
PostgreSQL 엔진 반환 (건조시럽 환산계수 DB)
|
||||
|
||||
Returns:
|
||||
Engine 또는 None (연결 실패 시)
|
||||
"""
|
||||
if self.postgres_engine is not None:
|
||||
return self.postgres_engine
|
||||
|
||||
try:
|
||||
self.postgres_engine = create_engine(
|
||||
DatabaseConfig.POSTGRES_URL,
|
||||
pool_size=5,
|
||||
max_overflow=5,
|
||||
pool_timeout=30,
|
||||
pool_recycle=1800,
|
||||
pool_pre_ping=True,
|
||||
echo=False
|
||||
)
|
||||
# 연결 테스트
|
||||
with self.postgres_engine.connect() as conn:
|
||||
conn.execute(text("SELECT 1"))
|
||||
print("[DB Manager] PostgreSQL 연결 성공")
|
||||
return self.postgres_engine
|
||||
except Exception as e:
|
||||
print(f"[DB Manager] PostgreSQL 연결 실패 (무시됨): {e}")
|
||||
self.postgres_engine = None
|
||||
return None
|
||||
|
||||
def get_postgres_session(self):
|
||||
"""
|
||||
PostgreSQL 세션 반환 (건조시럽 환산계수 조회용)
|
||||
|
||||
Returns:
|
||||
Session 또는 None (연결 실패 시)
|
||||
"""
|
||||
engine = self.get_postgres_engine()
|
||||
if engine is None:
|
||||
return None
|
||||
|
||||
if self.postgres_session is None:
|
||||
try:
|
||||
Session = sessionmaker(bind=engine)
|
||||
self.postgres_session = Session()
|
||||
except Exception as e:
|
||||
print(f"[DB Manager] PostgreSQL 세션 생성 실패: {e}")
|
||||
return None
|
||||
else:
|
||||
# 세션 상태 체크
|
||||
try:
|
||||
self.postgres_session.execute(text("SELECT 1"))
|
||||
except Exception as e:
|
||||
print(f"[DB Manager] PostgreSQL 세션 복구 시도: {e}")
|
||||
try:
|
||||
self.postgres_session.rollback()
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
self.postgres_session.close()
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
Session = sessionmaker(bind=engine)
|
||||
self.postgres_session = Session()
|
||||
except:
|
||||
self.postgres_session = None
|
||||
return None
|
||||
|
||||
return self.postgres_session
|
||||
|
||||
def get_conversion_factor(self, sung_code):
|
||||
"""
|
||||
건조시럽 환산계수 및 보관조건 조회
|
||||
|
||||
Args:
|
||||
sung_code: SUNG_CODE (예: "535000ASY")
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
'conversion_factor': float 또는 None,
|
||||
'ingredient_name': str 또는 None,
|
||||
'product_name': str 또는 None,
|
||||
'storage_conditions': str (기본값 '실온보관')
|
||||
}
|
||||
"""
|
||||
result = {
|
||||
'conversion_factor': None,
|
||||
'ingredient_name': None,
|
||||
'product_name': None,
|
||||
'storage_conditions': '실온보관' # 기본값
|
||||
}
|
||||
|
||||
session = self.get_postgres_session()
|
||||
if session is None:
|
||||
return result
|
||||
|
||||
try:
|
||||
query = text("""
|
||||
SELECT conversion_factor, ingredient_name, product_name, storage_conditions
|
||||
FROM drysyrup
|
||||
WHERE ingredient_code = :sung_code
|
||||
LIMIT 1
|
||||
""")
|
||||
row = session.execute(query, {'sung_code': sung_code}).fetchone()
|
||||
|
||||
if row:
|
||||
result['conversion_factor'] = float(row[0]) if row[0] is not None else None
|
||||
result['ingredient_name'] = row[1]
|
||||
result['product_name'] = row[2]
|
||||
# storage_conditions: 값이 있으면 사용, 없으면 기본값 '실온보관' 유지
|
||||
if row[3]:
|
||||
result['storage_conditions'] = row[3]
|
||||
except Exception as e:
|
||||
print(f"[DB Manager] 환산계수 조회 실패 (SUNG_CODE={sung_code}): {e}")
|
||||
# 세션 롤백
|
||||
try:
|
||||
session.rollback()
|
||||
except:
|
||||
pass
|
||||
|
||||
return result
|
||||
|
||||
def get_sqlite_connection(self, new_connection=False):
|
||||
"""
|
||||
SQLite mileage.db 연결 반환
|
||||
@ -237,7 +407,13 @@ class DatabaseManager:
|
||||
self.init_sqlite_schema()
|
||||
self.sqlite_conn = old_conn
|
||||
print(f"[DB Manager] SQLite 신규 DB 생성 완료: {self.sqlite_db_path}")
|
||||
|
||||
else:
|
||||
# 기존 DB: 마이그레이션 실행
|
||||
old_conn = self.sqlite_conn
|
||||
self.sqlite_conn = conn
|
||||
self._migrate_sqlite()
|
||||
self.sqlite_conn = old_conn
|
||||
|
||||
return conn
|
||||
|
||||
def init_sqlite_schema(self):
|
||||
@ -319,6 +495,67 @@ class DatabaseManager:
|
||||
self.sqlite_conn.commit()
|
||||
print("[DB Manager] SQLite 마이그레이션: ai_recommendations 테이블 생성")
|
||||
|
||||
# customer_identities 토큰 저장 컬럼 추가
|
||||
cursor.execute("PRAGMA table_info(customer_identities)")
|
||||
ci_columns = [row[1] for row in cursor.fetchall()]
|
||||
if 'access_token' not in ci_columns:
|
||||
cursor.execute("ALTER TABLE customer_identities ADD COLUMN access_token TEXT")
|
||||
cursor.execute("ALTER TABLE customer_identities ADD COLUMN refresh_token TEXT")
|
||||
cursor.execute("ALTER TABLE customer_identities ADD COLUMN token_expires_at DATETIME")
|
||||
self.sqlite_conn.commit()
|
||||
print("[DB Manager] SQLite 마이그레이션: customer_identities 토큰 컬럼 추가")
|
||||
|
||||
# pets 테이블 생성 (반려동물)
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='pets'")
|
||||
if not cursor.fetchone():
|
||||
cursor.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS pets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
name VARCHAR(50) NOT NULL,
|
||||
species VARCHAR(20) NOT NULL,
|
||||
breed VARCHAR(50),
|
||||
gender VARCHAR(10),
|
||||
birth_date DATE,
|
||||
age_months INTEGER,
|
||||
weight DECIMAL(5,2),
|
||||
photo_url TEXT,
|
||||
notes TEXT,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_pets_user ON pets(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_pets_species ON pets(species);
|
||||
""")
|
||||
self.sqlite_conn.commit()
|
||||
print("[DB Manager] SQLite 마이그레이션: pets 테이블 생성")
|
||||
|
||||
# otc_label_presets 테이블 생성 (OTC 용법 라벨)
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='otc_label_presets'")
|
||||
if not cursor.fetchone():
|
||||
cursor.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS otc_label_presets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
barcode VARCHAR(20) NOT NULL UNIQUE,
|
||||
drug_code VARCHAR(20),
|
||||
display_name VARCHAR(100),
|
||||
effect VARCHAR(100),
|
||||
dosage_instruction TEXT,
|
||||
usage_tip TEXT,
|
||||
use_wide_format BOOLEAN DEFAULT TRUE,
|
||||
print_count INTEGER DEFAULT 0,
|
||||
last_printed_at DATETIME,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_otc_label_barcode ON otc_label_presets(barcode);
|
||||
CREATE INDEX IF NOT EXISTS idx_otc_label_drug_code ON otc_label_presets(drug_code);
|
||||
""")
|
||||
self.sqlite_conn.commit()
|
||||
print("[DB Manager] SQLite 마이그레이션: otc_label_presets 테이블 생성")
|
||||
|
||||
def test_connection(self, database='PM_BASE'):
|
||||
"""연결 테스트"""
|
||||
try:
|
||||
@ -340,6 +577,20 @@ class DatabaseManager:
|
||||
if self.sqlite_conn:
|
||||
self.sqlite_conn.close()
|
||||
self.sqlite_conn = None
|
||||
|
||||
# PostgreSQL 연결 종료
|
||||
if self.postgres_session:
|
||||
try:
|
||||
self.postgres_session.close()
|
||||
except:
|
||||
pass
|
||||
self.postgres_session = None
|
||||
if self.postgres_engine:
|
||||
try:
|
||||
self.postgres_engine.dispose()
|
||||
except:
|
||||
pass
|
||||
self.postgres_engine = None
|
||||
|
||||
# 전역 데이터베이스 매니저 인스턴스
|
||||
db_manager = DatabaseManager()
|
||||
|
||||
220
backend/db/kims_logger.py
Normal file
@ -0,0 +1,220 @@
|
||||
"""
|
||||
KIMS API 로깅 모듈
|
||||
- API 호출/응답 SQLite 저장
|
||||
- AI 학습용 데이터 수집
|
||||
"""
|
||||
import sqlite3
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# DB 파일 경로
|
||||
DB_PATH = Path(__file__).parent / 'kims_logs.db'
|
||||
|
||||
def init_db():
|
||||
"""DB 초기화 (테이블 생성)"""
|
||||
schema_path = Path(__file__).parent / 'kims_logs_schema.sql'
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
with open(schema_path, 'r', encoding='utf-8') as f:
|
||||
schema = f.read()
|
||||
cursor.executescript(schema)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"KIMS 로그 DB 초기화 완료: {DB_PATH}")
|
||||
|
||||
def log_kims_call(
|
||||
pre_serial: str = None,
|
||||
user_id: int = None,
|
||||
source: str = 'admin',
|
||||
drug_codes: list = None,
|
||||
drug_names: list = None,
|
||||
api_status: str = 'SUCCESS',
|
||||
http_status: int = 200,
|
||||
response_time_ms: int = 0,
|
||||
interactions: list = None,
|
||||
response_raw: dict = None,
|
||||
error_message: str = None
|
||||
) -> int:
|
||||
"""
|
||||
KIMS API 호출 로그 저장
|
||||
|
||||
Returns:
|
||||
log_id: 생성된 로그 ID
|
||||
"""
|
||||
# DB 없으면 초기화
|
||||
if not DB_PATH.exists():
|
||||
init_db()
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
interactions = interactions or []
|
||||
drug_codes = drug_codes or []
|
||||
drug_names = drug_names or []
|
||||
|
||||
# 심각한 상호작용 여부 (severity 1 또는 2)
|
||||
has_severe = any(
|
||||
str(i.get('severity', '5')) in ['1', '2']
|
||||
for i in interactions
|
||||
)
|
||||
|
||||
# 메인 로그 삽입
|
||||
cursor.execute("""
|
||||
INSERT INTO kims_api_logs (
|
||||
pre_serial, user_id, source,
|
||||
request_drug_codes, request_drug_names, request_drug_count,
|
||||
api_status, http_status, response_time_ms,
|
||||
interaction_count, has_severe_interaction,
|
||||
interactions_json, response_raw, error_message
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""", (
|
||||
pre_serial,
|
||||
user_id,
|
||||
source,
|
||||
json.dumps(drug_codes, ensure_ascii=False),
|
||||
json.dumps(drug_names, ensure_ascii=False),
|
||||
len(drug_codes),
|
||||
api_status,
|
||||
http_status,
|
||||
response_time_ms,
|
||||
len(interactions),
|
||||
1 if has_severe else 0,
|
||||
json.dumps(interactions, ensure_ascii=False),
|
||||
json.dumps(response_raw, ensure_ascii=False) if response_raw else None,
|
||||
error_message
|
||||
))
|
||||
|
||||
log_id = cursor.lastrowid
|
||||
|
||||
# 상호작용 상세 삽입 (정규화)
|
||||
for inter in interactions:
|
||||
cursor.execute("""
|
||||
INSERT INTO kims_interactions (
|
||||
log_id,
|
||||
drug1_code, drug1_name, drug1_generic,
|
||||
drug2_code, drug2_name, drug2_generic,
|
||||
severity_level, severity_desc,
|
||||
likelihood_level, likelihood_desc,
|
||||
observation, observation_generic,
|
||||
clinical_management, action_to_take, reference
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""", (
|
||||
log_id,
|
||||
inter.get('drug1_code'),
|
||||
inter.get('drug1_name'),
|
||||
inter.get('generic1'),
|
||||
inter.get('drug2_code'),
|
||||
inter.get('drug2_name'),
|
||||
inter.get('generic2'),
|
||||
int(inter.get('severity', 5)) if str(inter.get('severity', '')).isdigit() else None,
|
||||
inter.get('severity_text'),
|
||||
None, # likelihood_level
|
||||
inter.get('likelihood'),
|
||||
inter.get('description'),
|
||||
None, # observation_generic
|
||||
inter.get('management'),
|
||||
inter.get('action'),
|
||||
None # reference
|
||||
))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return log_id
|
||||
|
||||
def get_recent_logs(limit: int = 50):
|
||||
"""최근 로그 조회"""
|
||||
if not DB_PATH.exists():
|
||||
return []
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("""
|
||||
SELECT * FROM kims_api_logs
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ?
|
||||
""", (limit,))
|
||||
|
||||
rows = cursor.fetchall()
|
||||
conn.close()
|
||||
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def get_log_detail(log_id: int):
|
||||
"""로그 상세 조회 (상호작용 포함)"""
|
||||
if not DB_PATH.exists():
|
||||
return None
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 메인 로그
|
||||
cursor.execute("SELECT * FROM kims_api_logs WHERE id = ?", (log_id,))
|
||||
log = cursor.fetchone()
|
||||
|
||||
if not log:
|
||||
conn.close()
|
||||
return None
|
||||
|
||||
# 상호작용 상세
|
||||
cursor.execute("""
|
||||
SELECT * FROM kims_interactions
|
||||
WHERE log_id = ?
|
||||
ORDER BY severity_level ASC
|
||||
""", (log_id,))
|
||||
interactions = cursor.fetchall()
|
||||
|
||||
conn.close()
|
||||
|
||||
result = dict(log)
|
||||
result['interactions_detail'] = [dict(i) for i in interactions]
|
||||
|
||||
return result
|
||||
|
||||
def get_stats():
|
||||
"""통계 조회"""
|
||||
if not DB_PATH.exists():
|
||||
return {}
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 전체 통계
|
||||
cursor.execute("""
|
||||
SELECT
|
||||
COUNT(*) as total_calls,
|
||||
SUM(CASE WHEN api_status = 'SUCCESS' THEN 1 ELSE 0 END) as success_count,
|
||||
SUM(CASE WHEN interaction_count > 0 THEN 1 ELSE 0 END) as with_interaction,
|
||||
SUM(CASE WHEN has_severe_interaction = 1 THEN 1 ELSE 0 END) as with_severe,
|
||||
AVG(response_time_ms) as avg_response_ms
|
||||
FROM kims_api_logs
|
||||
""")
|
||||
stats = dict(cursor.fetchone())
|
||||
|
||||
# 최근 7일 일별 통계
|
||||
cursor.execute("""
|
||||
SELECT * FROM kims_stats
|
||||
ORDER BY date DESC
|
||||
LIMIT 7
|
||||
""")
|
||||
daily = [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
conn.close()
|
||||
|
||||
stats['daily'] = daily
|
||||
return stats
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# DB 초기화 테스트
|
||||
init_db()
|
||||
print("KIMS 로그 DB 초기화 완료!")
|
||||
86
backend/db/kims_logs_schema.sql
Normal file
@ -0,0 +1,86 @@
|
||||
-- KIMS API 로그 테이블 스키마
|
||||
-- AI 학습 데이터로 활용 예정
|
||||
|
||||
-- 1. API 호출 로그 (메인)
|
||||
CREATE TABLE IF NOT EXISTS kims_api_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- 호출 컨텍스트
|
||||
pre_serial TEXT, -- 처방번호
|
||||
user_id INTEGER, -- 마일리지 회원 ID (있으면)
|
||||
source TEXT DEFAULT 'admin', -- 호출 소스 (admin, api, batch 등)
|
||||
|
||||
-- 요청 데이터
|
||||
request_drug_codes TEXT NOT NULL, -- JSON: ["055101150", "622801610"]
|
||||
request_drug_names TEXT, -- JSON: ["오메프투캡슐", "락소펜엠정"]
|
||||
request_drug_count INTEGER, -- 요청 약품 수
|
||||
|
||||
-- 응답 데이터
|
||||
api_status TEXT NOT NULL, -- SUCCESS, ERROR, TIMEOUT
|
||||
http_status INTEGER, -- HTTP 상태 코드
|
||||
response_time_ms INTEGER, -- 응답 시간 (밀리초)
|
||||
|
||||
-- 상호작용 결과
|
||||
interaction_count INTEGER DEFAULT 0, -- 발견된 상호작용 수
|
||||
has_severe_interaction INTEGER DEFAULT 0, -- 심각한 상호작용 여부 (1/2 등급)
|
||||
|
||||
-- 상세 데이터 (JSON)
|
||||
interactions_json TEXT, -- 상호작용 상세 정보 JSON
|
||||
response_raw TEXT, -- 전체 API 응답 (디버깅/학습용)
|
||||
|
||||
-- 에러 정보
|
||||
error_message TEXT
|
||||
);
|
||||
|
||||
-- 2. 상호작용 상세 (정규화, AI 학습용)
|
||||
CREATE TABLE IF NOT EXISTS kims_interactions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
log_id INTEGER NOT NULL, -- kims_api_logs.id FK
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- 약품 1
|
||||
drug1_code TEXT NOT NULL,
|
||||
drug1_name TEXT,
|
||||
drug1_generic TEXT, -- 성분명 (영문)
|
||||
|
||||
-- 약품 2
|
||||
drug2_code TEXT NOT NULL,
|
||||
drug2_name TEXT,
|
||||
drug2_generic TEXT, -- 성분명 (영문)
|
||||
|
||||
-- 상호작용 정보
|
||||
severity_level INTEGER, -- 1=심각, 2=중등도, 3=경미, 4=참고
|
||||
severity_desc TEXT, -- 심각도 설명 (중증, 경미 등)
|
||||
likelihood_level INTEGER, -- 발생 가능성
|
||||
likelihood_desc TEXT,
|
||||
|
||||
-- 상세 설명 (AI 학습 핵심 데이터)
|
||||
observation TEXT, -- 상호작용 설명 (한글)
|
||||
observation_generic TEXT, -- 일반적 설명
|
||||
clinical_management TEXT, -- 임상적 관리 방법
|
||||
action_to_take TEXT, -- 권장 조치
|
||||
reference TEXT, -- 참고문헌
|
||||
|
||||
FOREIGN KEY (log_id) REFERENCES kims_api_logs(id)
|
||||
);
|
||||
|
||||
-- 인덱스
|
||||
CREATE INDEX IF NOT EXISTS idx_kims_logs_created ON kims_api_logs(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_kims_logs_pre_serial ON kims_api_logs(pre_serial);
|
||||
CREATE INDEX IF NOT EXISTS idx_kims_logs_status ON kims_api_logs(api_status);
|
||||
CREATE INDEX IF NOT EXISTS idx_kims_interactions_log ON kims_interactions(log_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_kims_interactions_drugs ON kims_interactions(drug1_code, drug2_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_kims_interactions_severity ON kims_interactions(severity_level);
|
||||
|
||||
-- 통계 뷰
|
||||
CREATE VIEW IF NOT EXISTS kims_stats AS
|
||||
SELECT
|
||||
DATE(created_at) as date,
|
||||
COUNT(*) as total_calls,
|
||||
SUM(CASE WHEN api_status = 'SUCCESS' THEN 1 ELSE 0 END) as success_count,
|
||||
SUM(CASE WHEN interaction_count > 0 THEN 1 ELSE 0 END) as with_interaction,
|
||||
SUM(CASE WHEN has_severe_interaction = 1 THEN 1 ELSE 0 END) as with_severe,
|
||||
AVG(response_time_ms) as avg_response_ms
|
||||
FROM kims_api_logs
|
||||
GROUP BY DATE(created_at);
|
||||
@ -22,6 +22,9 @@ CREATE TABLE IF NOT EXISTS customer_identities (
|
||||
provider VARCHAR(20) NOT NULL,
|
||||
provider_user_id VARCHAR(100) NOT NULL,
|
||||
provider_data TEXT,
|
||||
access_token TEXT,
|
||||
refresh_token TEXT,
|
||||
token_expires_at DATETIME,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
UNIQUE(provider, provider_user_id)
|
||||
@ -120,3 +123,44 @@ CREATE TABLE IF NOT EXISTS ai_recommendations (
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rec_user_status ON ai_recommendations(user_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_rec_expires ON ai_recommendations(expires_at);
|
||||
|
||||
-- 8. 반려동물 테이블
|
||||
CREATE TABLE IF NOT EXISTS pets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
name VARCHAR(50) NOT NULL, -- 이름 (예: 뽀삐, 나비)
|
||||
species VARCHAR(20) NOT NULL, -- 종류: dog, cat, other
|
||||
breed VARCHAR(50), -- 품종 (말티즈, 페르시안 등)
|
||||
gender VARCHAR(10), -- male, female, unknown
|
||||
birth_date DATE, -- 생년월일 (나중에 사용)
|
||||
age_months INTEGER, -- 월령 (나중에 사용)
|
||||
weight DECIMAL(5,2), -- 체중 kg (나중에 사용)
|
||||
photo_url TEXT, -- 사진 URL
|
||||
notes TEXT, -- 특이사항/메모
|
||||
is_active BOOLEAN DEFAULT TRUE, -- 활성 상태
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_pets_user ON pets(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_pets_species ON pets(species);
|
||||
|
||||
-- 9. OTC 용법 라벨 테이블 (바코드 기준 오버라이드 데이터)
|
||||
CREATE TABLE IF NOT EXISTS otc_label_presets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
barcode VARCHAR(20) NOT NULL UNIQUE, -- 바코드 (PK 역할)
|
||||
drug_code VARCHAR(20), -- MSSQL DrugCode (참조용)
|
||||
display_name VARCHAR(100), -- 표시 이름 (오버라이드, NULL이면 MSSQL 이름 사용)
|
||||
effect VARCHAR(100), -- 효능 (예: "치통, 두통")
|
||||
dosage_instruction TEXT, -- 용법 (예: "1일 3회, 1회 1정, 식후 30분")
|
||||
usage_tip TEXT, -- 부가 설명 (예: "[통증 시에만 복용]")
|
||||
use_wide_format BOOLEAN DEFAULT TRUE, -- 와이드 포맷 사용 여부
|
||||
print_count INTEGER DEFAULT 0, -- 인쇄 횟수 (통계용)
|
||||
last_printed_at DATETIME, -- 마지막 인쇄 시간
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_otc_label_barcode ON otc_label_presets(barcode);
|
||||
CREATE INDEX IF NOT EXISTS idx_otc_label_drug_code ON otc_label_presets(drug_code);
|
||||
|
||||
351
backend/db/paai_logger.py
Normal file
@ -0,0 +1,351 @@
|
||||
"""
|
||||
PAAI (Pharmacist Assistant AI) 로깅 모듈
|
||||
- API 호출/응답 SQLite 저장
|
||||
- 분석 결과 및 피드백 관리
|
||||
"""
|
||||
import sqlite3
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
# DB 파일 경로
|
||||
DB_PATH = Path(__file__).parent / 'paai_logs.db'
|
||||
|
||||
|
||||
def init_db():
|
||||
"""DB 초기화 (테이블 생성)"""
|
||||
schema_path = Path(__file__).parent / 'paai_logs_schema.sql'
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
with open(schema_path, 'r', encoding='utf-8') as f:
|
||||
schema = f.read()
|
||||
cursor.executescript(schema)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"PAAI 로그 DB 초기화 완료: {DB_PATH}")
|
||||
|
||||
|
||||
def create_log(
|
||||
pre_serial: str = None,
|
||||
patient_code: str = None,
|
||||
patient_name: str = None,
|
||||
disease_code_1: str = None,
|
||||
disease_name_1: str = None,
|
||||
disease_code_2: str = None,
|
||||
disease_name_2: str = None,
|
||||
current_medications: list = None,
|
||||
previous_serial: str = None,
|
||||
previous_medications: list = None,
|
||||
prescription_changes: dict = None,
|
||||
otc_history: dict = None
|
||||
) -> int:
|
||||
"""
|
||||
PAAI 분석 로그 생성 (초기 상태)
|
||||
|
||||
Returns:
|
||||
log_id: 생성된 로그 ID
|
||||
"""
|
||||
if not DB_PATH.exists():
|
||||
init_db()
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
current_medications = current_medications or []
|
||||
previous_medications = previous_medications or []
|
||||
otc_history = otc_history or {}
|
||||
|
||||
# 환자명 마스킹
|
||||
masked_name = None
|
||||
if patient_name:
|
||||
masked_name = patient_name[0] + '*' * (len(patient_name) - 1) if len(patient_name) > 1 else patient_name
|
||||
|
||||
cursor.execute("""
|
||||
INSERT INTO paai_logs (
|
||||
pre_serial, patient_code, patient_name,
|
||||
disease_code_1, disease_name_1, disease_code_2, disease_name_2,
|
||||
current_medications, current_med_count,
|
||||
previous_serial, previous_medications, prescription_changes,
|
||||
otc_history, otc_visit_count,
|
||||
status
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
|
||||
""", (
|
||||
pre_serial,
|
||||
patient_code,
|
||||
masked_name,
|
||||
disease_code_1,
|
||||
disease_name_1,
|
||||
disease_code_2,
|
||||
disease_name_2,
|
||||
json.dumps(current_medications, ensure_ascii=False),
|
||||
len(current_medications),
|
||||
previous_serial,
|
||||
json.dumps(previous_medications, ensure_ascii=False),
|
||||
json.dumps(prescription_changes, ensure_ascii=False) if prescription_changes else None,
|
||||
json.dumps(otc_history, ensure_ascii=False),
|
||||
otc_history.get('visit_count', 0)
|
||||
))
|
||||
|
||||
log_id = cursor.lastrowid
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return log_id
|
||||
|
||||
|
||||
def update_kims_result(
|
||||
log_id: int,
|
||||
kims_drug_codes: list = None,
|
||||
kims_interactions: list = None,
|
||||
kims_response_time_ms: int = 0
|
||||
):
|
||||
"""KIMS 상호작용 결과 업데이트"""
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
kims_drug_codes = kims_drug_codes or []
|
||||
kims_interactions = kims_interactions or []
|
||||
|
||||
# 심각한 상호작용 여부 (severity 1 또는 2)
|
||||
has_severe = any(
|
||||
str(i.get('severity', '5')) in ['1', '2']
|
||||
for i in kims_interactions
|
||||
)
|
||||
|
||||
cursor.execute("""
|
||||
UPDATE paai_logs SET
|
||||
kims_drug_codes = ?,
|
||||
kims_drug_count = ?,
|
||||
kims_interactions = ?,
|
||||
kims_interaction_count = ?,
|
||||
kims_has_severe = ?,
|
||||
kims_response_time_ms = ?,
|
||||
status = 'kims_done'
|
||||
WHERE id = ?
|
||||
""", (
|
||||
json.dumps(kims_drug_codes, ensure_ascii=False),
|
||||
len(kims_drug_codes),
|
||||
json.dumps(kims_interactions, ensure_ascii=False),
|
||||
len(kims_interactions),
|
||||
1 if has_severe else 0,
|
||||
kims_response_time_ms,
|
||||
log_id
|
||||
))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_ai_result(
|
||||
log_id: int,
|
||||
ai_prompt: str = None,
|
||||
ai_model: str = None,
|
||||
ai_response: dict = None,
|
||||
ai_response_time_ms: int = 0,
|
||||
ai_token_count: int = None
|
||||
):
|
||||
"""AI 분석 결과 업데이트"""
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("""
|
||||
UPDATE paai_logs SET
|
||||
ai_prompt = ?,
|
||||
ai_model = ?,
|
||||
ai_response = ?,
|
||||
ai_response_time_ms = ?,
|
||||
ai_token_count = ?,
|
||||
status = 'success'
|
||||
WHERE id = ?
|
||||
""", (
|
||||
ai_prompt,
|
||||
ai_model,
|
||||
json.dumps(ai_response, ensure_ascii=False) if ai_response else None,
|
||||
ai_response_time_ms,
|
||||
ai_token_count,
|
||||
log_id
|
||||
))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_error(log_id: int, error_message: str):
|
||||
"""에러 상태 업데이트"""
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("""
|
||||
UPDATE paai_logs SET
|
||||
status = 'error',
|
||||
error_message = ?
|
||||
WHERE id = ?
|
||||
""", (error_message, log_id))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_feedback(log_id: int, useful: bool, comment: str = None):
|
||||
"""피드백 업데이트"""
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("""
|
||||
UPDATE paai_logs SET
|
||||
feedback_useful = ?,
|
||||
feedback_comment = ?
|
||||
WHERE id = ?
|
||||
""", (1 if useful else 0, comment, log_id))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_recent_logs(
|
||||
limit: int = 100,
|
||||
status: str = None,
|
||||
has_severe: bool = None,
|
||||
date: str = None
|
||||
) -> list:
|
||||
"""최근 로그 조회"""
|
||||
if not DB_PATH.exists():
|
||||
return []
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
|
||||
query = "SELECT * FROM paai_logs WHERE 1=1"
|
||||
params = []
|
||||
|
||||
if status:
|
||||
query += " AND status = ?"
|
||||
params.append(status)
|
||||
|
||||
if has_severe is not None:
|
||||
query += " AND kims_has_severe = ?"
|
||||
params.append(1 if has_severe else 0)
|
||||
|
||||
if date:
|
||||
query += " AND DATE(created_at) = ?"
|
||||
params.append(date)
|
||||
|
||||
query += " ORDER BY created_at DESC LIMIT ?"
|
||||
params.append(limit)
|
||||
|
||||
cursor.execute(query, params)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
result = []
|
||||
for row in rows:
|
||||
log = dict(row)
|
||||
# JSON 필드 파싱
|
||||
for field in ['current_medications', 'previous_medications', 'prescription_changes',
|
||||
'otc_history', 'kims_drug_codes', 'kims_interactions', 'ai_response']:
|
||||
if log.get(field):
|
||||
try:
|
||||
log[field] = json.loads(log[field])
|
||||
except:
|
||||
pass
|
||||
result.append(log)
|
||||
|
||||
conn.close()
|
||||
return result
|
||||
|
||||
|
||||
def get_log_detail(log_id: int) -> dict:
|
||||
"""로그 상세 조회"""
|
||||
if not DB_PATH.exists():
|
||||
return None
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("SELECT * FROM paai_logs WHERE id = ?", (log_id,))
|
||||
row = cursor.fetchone()
|
||||
|
||||
if not row:
|
||||
conn.close()
|
||||
return None
|
||||
|
||||
log = dict(row)
|
||||
|
||||
# JSON 필드 파싱
|
||||
for field in ['current_medications', 'previous_medications', 'prescription_changes',
|
||||
'otc_history', 'kims_drug_codes', 'kims_interactions', 'ai_response']:
|
||||
if log.get(field):
|
||||
try:
|
||||
log[field] = json.loads(log[field])
|
||||
except:
|
||||
pass
|
||||
|
||||
conn.close()
|
||||
return log
|
||||
|
||||
|
||||
def get_stats() -> dict:
|
||||
"""통계 조회"""
|
||||
if not DB_PATH.exists():
|
||||
return {
|
||||
'total': 0,
|
||||
'today': 0,
|
||||
'success_rate': 0,
|
||||
'avg_response_time': 0,
|
||||
'severe_count': 0
|
||||
}
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
cursor = conn.cursor()
|
||||
|
||||
today = datetime.now().strftime('%Y-%m-%d')
|
||||
|
||||
# 전체 건수
|
||||
cursor.execute("SELECT COUNT(*) FROM paai_logs")
|
||||
total = cursor.fetchone()[0]
|
||||
|
||||
# 오늘 건수
|
||||
cursor.execute("SELECT COUNT(*) FROM paai_logs WHERE DATE(created_at) = ?", (today,))
|
||||
today_count = cursor.fetchone()[0]
|
||||
|
||||
# 성공률
|
||||
cursor.execute("SELECT COUNT(*) FROM paai_logs WHERE status = 'success'")
|
||||
success_count = cursor.fetchone()[0]
|
||||
success_rate = (success_count / total * 100) if total > 0 else 0
|
||||
|
||||
# 평균 응답시간
|
||||
cursor.execute("SELECT AVG(ai_response_time_ms) FROM paai_logs WHERE ai_response_time_ms > 0")
|
||||
avg_time = cursor.fetchone()[0] or 0
|
||||
|
||||
# 심각한 상호작용 건수 (오늘)
|
||||
cursor.execute("""
|
||||
SELECT COUNT(*) FROM paai_logs
|
||||
WHERE DATE(created_at) = ? AND kims_has_severe = 1
|
||||
""", (today,))
|
||||
severe_count = cursor.fetchone()[0]
|
||||
|
||||
# 피드백 통계
|
||||
cursor.execute("SELECT COUNT(*) FROM paai_logs WHERE feedback_useful = 1")
|
||||
useful_count = cursor.fetchone()[0]
|
||||
cursor.execute("SELECT COUNT(*) FROM paai_logs WHERE feedback_useful IS NOT NULL")
|
||||
feedback_total = cursor.fetchone()[0]
|
||||
|
||||
conn.close()
|
||||
|
||||
return {
|
||||
'total': total,
|
||||
'today': today_count,
|
||||
'success_rate': round(success_rate, 1),
|
||||
'avg_response_time': int(avg_time),
|
||||
'severe_count': severe_count,
|
||||
'feedback': {
|
||||
'useful': useful_count,
|
||||
'total': feedback_total,
|
||||
'rate': round(useful_count / feedback_total * 100, 1) if feedback_total > 0 else 0
|
||||
}
|
||||
}
|
||||
59
backend/db/paai_logs_schema.sql
Normal file
@ -0,0 +1,59 @@
|
||||
-- PAAI (Pharmacist Assistant AI) 로그 스키마
|
||||
-- 생성일: 2026-03-04
|
||||
|
||||
CREATE TABLE IF NOT EXISTS paai_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- 요청 정보
|
||||
pre_serial TEXT, -- 처방번호
|
||||
patient_code TEXT, -- 환자코드 (CusCode)
|
||||
patient_name TEXT, -- 환자명 (마스킹: 김**)
|
||||
|
||||
-- 질병 정보
|
||||
disease_code_1 TEXT, -- St1 (상병코드1)
|
||||
disease_name_1 TEXT, -- 상병명1
|
||||
disease_code_2 TEXT, -- St2 (상병코드2)
|
||||
disease_name_2 TEXT, -- 상병명2
|
||||
|
||||
-- 처방 정보
|
||||
current_medications TEXT, -- JSON: 현재 처방 [{code, name, dosage, ...}]
|
||||
current_med_count INTEGER, -- 현재 처방 약품 수
|
||||
previous_serial TEXT, -- 이전 처방번호
|
||||
previous_medications TEXT, -- JSON: 이전 처방
|
||||
prescription_changes TEXT, -- JSON: {added, removed, changed}
|
||||
|
||||
-- OTC 이력
|
||||
otc_history TEXT, -- JSON: {purchases, frequent_items}
|
||||
otc_visit_count INTEGER, -- OTC 구매 횟수
|
||||
|
||||
-- KIMS 상호작용
|
||||
kims_drug_codes TEXT, -- JSON: 검사한 KD코드 배열
|
||||
kims_drug_count INTEGER, -- 검사한 약품 수
|
||||
kims_interactions TEXT, -- JSON: 상호작용 결과
|
||||
kims_interaction_count INTEGER, -- 상호작용 건수
|
||||
kims_has_severe BOOLEAN DEFAULT 0, -- 심각한 상호작용 (severity 1,2)
|
||||
kims_response_time_ms INTEGER, -- KIMS API 응답시간
|
||||
|
||||
-- AI 분석
|
||||
ai_prompt TEXT, -- AI에 전달한 프롬프트
|
||||
ai_model TEXT, -- 사용된 모델
|
||||
ai_response TEXT, -- JSON: AI 분석 결과
|
||||
ai_response_time_ms INTEGER, -- AI 응답 시간
|
||||
ai_token_count INTEGER, -- 토큰 사용량
|
||||
|
||||
-- 상태
|
||||
status TEXT DEFAULT 'pending', -- pending, kims_done, success, error
|
||||
error_message TEXT,
|
||||
|
||||
-- 피드백
|
||||
feedback_useful INTEGER, -- 1=유용, 0=아님, NULL=미응답
|
||||
feedback_comment TEXT -- 약사 코멘트
|
||||
);
|
||||
|
||||
-- 인덱스
|
||||
CREATE INDEX IF NOT EXISTS idx_paai_created ON paai_logs(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_paai_patient ON paai_logs(patient_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_paai_status ON paai_logs(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_paai_serial ON paai_logs(pre_serial);
|
||||
CREATE INDEX IF NOT EXISTS idx_paai_severe ON paai_logs(kims_has_severe);
|
||||
38
backend/db/product_images_schema.sql
Normal file
@ -0,0 +1,38 @@
|
||||
-- product_images.db 스키마
|
||||
-- yakkok.com에서 크롤링한 제품 이미지 저장
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product_images (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
barcode TEXT UNIQUE NOT NULL, -- 바코드 (고유키)
|
||||
drug_code TEXT, -- PIT3000 DrugCode
|
||||
product_name TEXT NOT NULL, -- 제품명
|
||||
search_name TEXT, -- 검색에 사용한 이름
|
||||
image_base64 TEXT, -- 이미지 (base64)
|
||||
image_url TEXT, -- 원본 URL
|
||||
thumbnail_base64 TEXT, -- 썸네일 (base64, 작은 사이즈)
|
||||
source TEXT DEFAULT 'yakkok', -- 출처
|
||||
status TEXT DEFAULT 'pending', -- pending/success/failed/manual/no_result
|
||||
error_message TEXT, -- 실패 시 에러 메시지
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- 인덱스
|
||||
CREATE INDEX IF NOT EXISTS idx_barcode ON product_images(barcode);
|
||||
CREATE INDEX IF NOT EXISTS idx_status ON product_images(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_drug_code ON product_images(drug_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_created_at ON product_images(created_at);
|
||||
|
||||
-- 크롤링 로그 테이블
|
||||
CREATE TABLE IF NOT EXISTS crawl_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
batch_id TEXT, -- 배치 ID
|
||||
total_count INTEGER DEFAULT 0, -- 전체 개수
|
||||
success_count INTEGER DEFAULT 0, -- 성공 개수
|
||||
failed_count INTEGER DEFAULT 0, -- 실패 개수
|
||||
skipped_count INTEGER DEFAULT 0, -- 스킵 개수 (이미 있음)
|
||||
started_at DATETIME,
|
||||
finished_at DATETIME,
|
||||
status TEXT DEFAULT 'running', -- running/completed/failed
|
||||
error_message TEXT
|
||||
);
|
||||
267
backend/dongwon_api.py
Normal file
@ -0,0 +1,267 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
동원약품 도매상 API - Flask Blueprint
|
||||
|
||||
핵심 로직은 wholesale 패키지에서 가져옴
|
||||
이 파일은 Flask 웹 API 연동만 담당
|
||||
"""
|
||||
|
||||
import time
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request as flask_request
|
||||
|
||||
# wholesale 패키지 경로 설정
|
||||
import wholesale_path
|
||||
|
||||
# wholesale 패키지에서 핵심 클래스 가져오기
|
||||
from wholesale import DongwonSession
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Blueprint 생성
|
||||
dongwon_bp = Blueprint('dongwon', __name__, url_prefix='/api/dongwon')
|
||||
|
||||
|
||||
# ========== 세션 관리 ==========
|
||||
|
||||
_dongwon_session = None
|
||||
|
||||
def get_dongwon_session():
|
||||
global _dongwon_session
|
||||
if _dongwon_session is None:
|
||||
_dongwon_session = DongwonSession()
|
||||
return _dongwon_session
|
||||
|
||||
|
||||
def search_dongwon_stock(keyword: str, search_type: str = 'name'):
|
||||
"""동원약품 재고 검색"""
|
||||
try:
|
||||
session = get_dongwon_session()
|
||||
result = session.search_products(keyword)
|
||||
|
||||
if result.get('success'):
|
||||
return {
|
||||
'success': True,
|
||||
'keyword': keyword,
|
||||
'search_type': search_type,
|
||||
'count': result.get('total', 0),
|
||||
'items': result.get('items', [])
|
||||
}
|
||||
else:
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"동원약품 검색 오류: {e}")
|
||||
return {'success': False, 'error': 'SEARCH_ERROR', 'message': str(e)}
|
||||
|
||||
|
||||
# ========== Flask API Routes ==========
|
||||
|
||||
@dongwon_bp.route('/stock', methods=['GET'])
|
||||
def api_dongwon_stock():
|
||||
"""
|
||||
동원약품 재고 조회 API
|
||||
|
||||
GET /api/dongwon/stock?keyword=타이레놀
|
||||
"""
|
||||
keyword = flask_request.args.get('keyword', '').strip()
|
||||
|
||||
if not keyword:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'keyword 파라미터가 필요합니다.'
|
||||
}), 400
|
||||
|
||||
result = search_dongwon_stock(keyword)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@dongwon_bp.route('/session', methods=['GET'])
|
||||
def api_dongwon_session():
|
||||
"""동원약품 세션 상태 확인"""
|
||||
session = get_dongwon_session()
|
||||
return jsonify({
|
||||
'logged_in': getattr(session, '_logged_in', False),
|
||||
'last_login': getattr(session, '_last_login', 0),
|
||||
'session_age_sec': int(time.time() - session._last_login) if getattr(session, '_last_login', 0) else None
|
||||
})
|
||||
|
||||
|
||||
@dongwon_bp.route('/balance', methods=['GET'])
|
||||
def api_dongwon_balance():
|
||||
"""
|
||||
동원약품 잔고 조회 API
|
||||
|
||||
GET /api/dongwon/balance
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"balance": 7080018, // 당월 잔고
|
||||
"prev_balance": 5407528, // 전월 잔고
|
||||
"trade_amount": 1672490, // 거래 금액
|
||||
"payment_amount": 0 // 결제 금액
|
||||
}
|
||||
"""
|
||||
try:
|
||||
session = get_dongwon_session()
|
||||
result = session.get_balance()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"동원약품 잔고 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'BALANCE_ERROR',
|
||||
'message': str(e),
|
||||
'balance': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@dongwon_bp.route('/monthly-orders', methods=['GET'])
|
||||
def api_dongwon_monthly_orders():
|
||||
"""
|
||||
동원약품 월간 주문 조회 API
|
||||
|
||||
GET /api/dongwon/monthly-orders?year=2026&month=3
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"year": 2026,
|
||||
"month": 3,
|
||||
"total_amount": 1815115, // 주문 총액
|
||||
"approved_amount": 1672490, // 승인 금액
|
||||
"order_count": 23 // 주문 건수
|
||||
}
|
||||
"""
|
||||
year = flask_request.args.get('year', type=int)
|
||||
month = flask_request.args.get('month', type=int)
|
||||
|
||||
# 기본값: 현재 월
|
||||
if not year or not month:
|
||||
now = datetime.now()
|
||||
year = year or now.year
|
||||
month = month or now.month
|
||||
|
||||
try:
|
||||
session = get_dongwon_session()
|
||||
result = session.get_monthly_orders(year, month)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"동원약품 월간 주문 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MONTHLY_ORDERS_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@dongwon_bp.route('/cart', methods=['GET'])
|
||||
def api_dongwon_cart():
|
||||
"""
|
||||
동원약품 장바구니 조회 API
|
||||
|
||||
GET /api/dongwon/cart
|
||||
"""
|
||||
try:
|
||||
session = get_dongwon_session()
|
||||
result = session.get_cart()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"동원약품 장바구니 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'CART_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@dongwon_bp.route('/cart/add', methods=['POST'])
|
||||
def api_dongwon_cart_add():
|
||||
"""
|
||||
동원약품 장바구니 추가 API
|
||||
|
||||
POST /api/dongwon/cart/add
|
||||
{
|
||||
"item_code": "A4394",
|
||||
"quantity": 2
|
||||
}
|
||||
"""
|
||||
data = flask_request.get_json() or {}
|
||||
item_code = data.get('item_code', '').strip()
|
||||
quantity = data.get('quantity', 1)
|
||||
|
||||
if not item_code:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'item_code가 필요합니다.'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
session = get_dongwon_session()
|
||||
result = session.add_to_cart(item_code, quantity)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"동원약품 장바구니 추가 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'CART_ADD_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@dongwon_bp.route('/orders/summary-by-kd', methods=['GET'])
|
||||
def api_dongwon_orders_by_kd():
|
||||
"""
|
||||
동원약품 주문량 KD코드별 집계 API
|
||||
|
||||
GET /api/dongwon/orders/summary-by-kd?start_date=2026-03-01&end_date=2026-03-07
|
||||
|
||||
흐름:
|
||||
1. 주문 목록 API → 주문번호 목록
|
||||
2. 각 주문번호 → HTML 파싱 → ItemCode 목록
|
||||
3. 각 ItemCode → itemInfoAx → KD코드, 규격, 수량
|
||||
4. KD코드별 집계
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"order_count": 4,
|
||||
"by_kd_code": {
|
||||
"642900680": {
|
||||
"product_name": "사미온정10mg",
|
||||
"spec": "30정(병)",
|
||||
"boxes": 3,
|
||||
"units": 90
|
||||
}
|
||||
},
|
||||
"total_products": 15
|
||||
}
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
today = datetime.now()
|
||||
start_date = flask_request.args.get('start_date', today.strftime("%Y-%m-%d")).strip()
|
||||
end_date = flask_request.args.get('end_date', today.strftime("%Y-%m-%d")).strip()
|
||||
|
||||
try:
|
||||
session = get_dongwon_session()
|
||||
|
||||
# 새로운 get_orders_by_kd_code 메서드 사용
|
||||
result = session.get_orders_by_kd_code(start_date, end_date)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"동원약품 주문량 집계 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e),
|
||||
'by_kd_code': {},
|
||||
'order_count': 0
|
||||
}), 500
|
||||
85
backend/download_js.py
Normal file
@ -0,0 +1,85 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""지오영 JS 파일 다운로드 및 분석"""
|
||||
|
||||
import requests
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
import re
|
||||
|
||||
async def download_and_analyze():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
# 로그인
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
cookies = await page.context.cookies()
|
||||
await browser.close()
|
||||
|
||||
# 세션 설정
|
||||
session = requests.Session()
|
||||
for c in cookies:
|
||||
session.cookies.set(c['name'], c['value'])
|
||||
|
||||
# JS 파일 다운로드
|
||||
js_urls = [
|
||||
'https://gwn.geoweb.kr/bundles/order_product_cart?v=JPwFQ8DWaNMW1VmbtWYKTJqxT-5255z351W5iZE1qew1',
|
||||
'https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1'
|
||||
]
|
||||
|
||||
for url in js_urls:
|
||||
print(f"\n{'='*60}")
|
||||
print(f"분석: {url.split('/')[-1].split('?')[0]}")
|
||||
print('='*60)
|
||||
|
||||
resp = session.get(url)
|
||||
content = resp.text
|
||||
|
||||
# 장바구니/주문 관련 함수 찾기
|
||||
patterns = [
|
||||
(r'function\s+(fn\w*Cart\w*|add\w*Cart\w*|insert\w*Order\w*)\s*\([^)]*\)', 'function'),
|
||||
(r'(fn\w*Cart\w*|add\w*Cart\w*)\s*=\s*function', 'var function'),
|
||||
(r'url\s*:\s*["\']([^"\']*(?:Cart|Order|Add)[^"\']*)["\']', 'ajax url'),
|
||||
(r'\$\.(?:ajax|post|get)\s*\(\s*["\']([^"\']+)["\']', 'ajax call'),
|
||||
]
|
||||
|
||||
found = {}
|
||||
for pattern, name in patterns:
|
||||
matches = re.findall(pattern, content, re.IGNORECASE)
|
||||
if matches:
|
||||
for m in matches:
|
||||
if m not in found:
|
||||
found[m] = name
|
||||
|
||||
for item, ptype in found.items():
|
||||
print(f"[{ptype}] {item}")
|
||||
|
||||
# InsertOrder 함수 찾기
|
||||
if 'InsertOrder' in content or 'insertOrder' in content:
|
||||
print("\n--- InsertOrder 함수 발견! ---")
|
||||
# 해당 부분 추출
|
||||
idx = content.lower().find('insertorder')
|
||||
if idx > 0:
|
||||
snippet = content[max(0, idx-100):idx+500]
|
||||
print(snippet[:600])
|
||||
|
||||
# AddCart 패턴 찾기
|
||||
add_patterns = re.findall(r'.{50}AddCart.{100}|.{50}addCart.{100}', content, re.IGNORECASE)
|
||||
if add_patterns:
|
||||
print("\n--- AddCart 관련 ---")
|
||||
for p in add_patterns[:3]:
|
||||
print(p)
|
||||
|
||||
# ajax 호출 상세
|
||||
ajax_pattern = r'\$\.ajax\s*\(\s*\{[^}]{50,500}(Cart|Order)[^}]{0,200}\}'
|
||||
ajax_matches = re.findall(ajax_pattern, content, re.IGNORECASE | re.DOTALL)
|
||||
if ajax_matches:
|
||||
print(f"\n--- AJAX 호출 {len(ajax_matches)}개 발견 ---")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(download_and_analyze())
|
||||
18
backend/ecosystem.config.js
Normal file
@ -0,0 +1,18 @@
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: 'pharmacy-flask',
|
||||
script: 'python',
|
||||
args: 'app.py',
|
||||
cwd: 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend',
|
||||
interpreter: 'none',
|
||||
watch: false,
|
||||
autorestart: true,
|
||||
max_restarts: 10,
|
||||
env: {
|
||||
FLASK_ENV: 'production',
|
||||
PYTHONIOENCODING: 'utf-8'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
86
backend/extract_addcart.py
Normal file
@ -0,0 +1,86 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AddCart 함수 전체 추출"""
|
||||
|
||||
import requests
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
import re
|
||||
|
||||
async def extract():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
cookies = await page.context.cookies()
|
||||
await browser.close()
|
||||
|
||||
session = requests.Session()
|
||||
for c in cookies:
|
||||
session.cookies.set(c['name'], c['value'])
|
||||
|
||||
resp = session.get('https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1')
|
||||
content = resp.text
|
||||
|
||||
# AddCart 함수 전체 찾기
|
||||
# function AddCart(n,t,i){ ... }
|
||||
start = content.find('function AddCart')
|
||||
if start > 0:
|
||||
# 중괄호 매칭으로 함수 끝 찾기
|
||||
depth = 0
|
||||
end = start
|
||||
in_func = False
|
||||
|
||||
for i in range(start, min(start + 5000, len(content))):
|
||||
if content[i] == '{':
|
||||
depth += 1
|
||||
in_func = True
|
||||
elif content[i] == '}':
|
||||
depth -= 1
|
||||
if in_func and depth == 0:
|
||||
end = i + 1
|
||||
break
|
||||
|
||||
func_content = content[start:end]
|
||||
print("="*60)
|
||||
print("AddCart 함수 전체:")
|
||||
print("="*60)
|
||||
print(func_content)
|
||||
|
||||
# ajax 호출 찾기
|
||||
ajax_match = re.search(r'\$\.ajax\s*\(\s*\{[^}]+\}', func_content, re.DOTALL)
|
||||
if ajax_match:
|
||||
print("\n" + "="*60)
|
||||
print("AJAX 호출:")
|
||||
print("="*60)
|
||||
print(ajax_match.group())
|
||||
|
||||
# InsertOrder 함수도 찾기
|
||||
start2 = content.find('function InsertOrder')
|
||||
if start2 > 0:
|
||||
depth = 0
|
||||
end2 = start2
|
||||
in_func = False
|
||||
|
||||
for i in range(start2, min(start2 + 3000, len(content))):
|
||||
if content[i] == '{':
|
||||
depth += 1
|
||||
in_func = True
|
||||
elif content[i] == '}':
|
||||
depth -= 1
|
||||
if in_func and depth == 0:
|
||||
end2 = i + 1
|
||||
break
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("InsertOrder 함수:")
|
||||
print("="*60)
|
||||
print(content[start2:end2][:1500])
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(extract())
|
||||
71
backend/extract_processcart.py
Normal file
@ -0,0 +1,71 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ProcessCart 함수 추출"""
|
||||
|
||||
import requests
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
async def extract():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
cookies = await page.context.cookies()
|
||||
await browser.close()
|
||||
|
||||
session = requests.Session()
|
||||
for c in cookies:
|
||||
session.cookies.set(c['name'], c['value'])
|
||||
|
||||
resp = session.get('https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1')
|
||||
content = resp.text
|
||||
|
||||
# ProcessCart 함수 찾기
|
||||
start = content.find('function ProcessCart')
|
||||
if start > 0:
|
||||
depth = 0
|
||||
end = start
|
||||
in_func = False
|
||||
|
||||
for i in range(start, min(start + 5000, len(content))):
|
||||
if content[i] == '{':
|
||||
depth += 1
|
||||
in_func = True
|
||||
elif content[i] == '}':
|
||||
depth -= 1
|
||||
if in_func and depth == 0:
|
||||
end = i + 1
|
||||
break
|
||||
|
||||
func_content = content[start:end]
|
||||
print("="*60)
|
||||
print("ProcessCart 함수:")
|
||||
print("="*60)
|
||||
print(func_content)
|
||||
else:
|
||||
# 다른 패턴으로 찾기
|
||||
print("ProcessCart를 변수로 찾기...")
|
||||
start = content.find('ProcessCart=function')
|
||||
if start > 0:
|
||||
print(content[start:start+2000])
|
||||
else:
|
||||
# ajax 호출 찾기
|
||||
import re
|
||||
ajax_calls = re.findall(r'\$\.ajax\s*\(\s*\{[^}]{100,1000}(Cart|Order)[^}]{0,500}\}', content, re.IGNORECASE | re.DOTALL)
|
||||
print(f"\nAJAX 호출 {len(ajax_calls)}개 발견")
|
||||
|
||||
# url 패턴 찾기
|
||||
urls = re.findall(r'url\s*:\s*["\']([^"\']+)["\']', content)
|
||||
print("\n모든 URL:")
|
||||
for url in set(urls):
|
||||
if 'Cart' in url or 'Order' in url or 'Add' in url or 'Insert' in url:
|
||||
print(f" {url}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(extract())
|
||||
90
backend/find_cart_js.py
Normal file
@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""지오영 JavaScript에서 장바구니 추가 함수 찾기"""
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
import re
|
||||
|
||||
async def analyze_js():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
# 로그인
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
# 메인 페이지
|
||||
await page.goto('https://gwn.geoweb.kr/Home/Index')
|
||||
await page.wait_for_timeout(3000)
|
||||
|
||||
# 모든 스크립트 태그 내용 가져오기
|
||||
scripts = await page.evaluate('''() => {
|
||||
var result = [];
|
||||
var scripts = document.querySelectorAll('script');
|
||||
scripts.forEach(s => {
|
||||
if (s.src) {
|
||||
result.push({type: 'src', url: s.src});
|
||||
}
|
||||
if (s.textContent && s.textContent.length > 100) {
|
||||
result.push({type: 'inline', content: s.textContent});
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}''')
|
||||
|
||||
print(f"스크립트 {len(scripts)}개 발견")
|
||||
|
||||
# 장바구니 관련 함수 찾기
|
||||
for s in scripts:
|
||||
if s['type'] == 'inline':
|
||||
content = s['content']
|
||||
# 담기, Cart, Add 관련 찾기
|
||||
if '담기' in content or 'AddCart' in content or 'addCart' in content or 'InsertOrder' in content:
|
||||
print("\n" + "="*60)
|
||||
print("장바구니 관련 스크립트 발견!")
|
||||
print("="*60)
|
||||
|
||||
# 함수 정의 찾기
|
||||
func_patterns = [
|
||||
r'function\s+(\w*[Cc]art\w*)\s*\([^)]*\)\s*{[^}]+}',
|
||||
r'function\s+(\w*[Aa]dd\w*)\s*\([^)]*\)\s*{[^}]+}',
|
||||
r'(\w+)\s*=\s*function\s*\([^)]*\)\s*{[^}]*[Cc]art[^}]*}',
|
||||
]
|
||||
|
||||
for pattern in func_patterns:
|
||||
matches = re.findall(pattern, content, re.DOTALL)
|
||||
for m in matches:
|
||||
print(f"함수 발견: {m}")
|
||||
|
||||
# ajax 호출 찾기
|
||||
ajax_pattern = r'\$\.ajax\s*\(\s*{[^}]+url[^}]+}'
|
||||
ajax_matches = re.findall(ajax_pattern, content, re.DOTALL)
|
||||
for m in ajax_matches:
|
||||
if 'cart' in m.lower() or 'order' in m.lower() or 'add' in m.lower():
|
||||
print(f"\nAJAX 호출:\n{m[:500]}")
|
||||
|
||||
# 일부 내용 출력
|
||||
lines = content.split('\n')
|
||||
for i, line in enumerate(lines):
|
||||
if '담기' in line or 'addCart' in line.lower() or 'insertorder' in line.lower():
|
||||
print(f"\n관련 라인 {i}:")
|
||||
print('\n'.join(lines[max(0,i-3):min(len(lines),i+10)]))
|
||||
|
||||
# 외부 JS 파일 확인
|
||||
print("\n" + "="*60)
|
||||
print("외부 스크립트 파일:")
|
||||
print("="*60)
|
||||
for s in scripts:
|
||||
if s['type'] == 'src':
|
||||
print(s['url'])
|
||||
|
||||
await browser.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(analyze_js())
|
||||
82
backend/find_frmsave.py
Normal file
@ -0,0 +1,82 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""frmSave 폼과 주문 저장 로직 찾기"""
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
import re
|
||||
|
||||
async def analyze():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
# 네트워크 요청 캡처
|
||||
requests_log = []
|
||||
def log_req(req):
|
||||
if req.method == 'POST':
|
||||
requests_log.append({'url': req.url, 'data': req.post_data})
|
||||
page.on('request', log_req)
|
||||
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
# 메인 페이지
|
||||
await page.goto('https://gwn.geoweb.kr/Home/Index')
|
||||
await page.wait_for_timeout(2000)
|
||||
|
||||
# 페이지 HTML에서 frmSave 폼 찾기
|
||||
html = await page.content()
|
||||
|
||||
print("="*60)
|
||||
print("frmSave 폼 찾기:")
|
||||
print("="*60)
|
||||
|
||||
soup = BeautifulSoup(html, 'html.parser')
|
||||
|
||||
# 모든 form 찾기
|
||||
forms = soup.find_all('form')
|
||||
for form in forms:
|
||||
form_id = form.get('id', '')
|
||||
form_action = form.get('action', '')
|
||||
print(f"폼: id={form_id}, action={form_action}")
|
||||
|
||||
if 'save' in form_id.lower() or 'order' in form_id.lower():
|
||||
print(f" >>> 주문 관련 폼 발견!")
|
||||
inputs = form.find_all('input')
|
||||
for inp in inputs[:10]:
|
||||
print(f" - {inp.get('name')}: {inp.get('value', '')[:30]}")
|
||||
|
||||
# 주문저장 버튼 찾기
|
||||
print("\n" + "="*60)
|
||||
print("주문저장 버튼:")
|
||||
print("="*60)
|
||||
|
||||
buttons = soup.find_all(['button', 'input'], type=['button', 'submit'])
|
||||
for btn in buttons:
|
||||
text = btn.get_text(strip=True) or btn.get('value', '')
|
||||
onclick = btn.get('onclick', '')
|
||||
if '저장' in text or '주문' in text:
|
||||
print(f"버튼: {text}")
|
||||
print(f" onclick: {onclick[:100]}")
|
||||
|
||||
# JavaScript에서 폼 action 찾기
|
||||
scripts = soup.find_all('script')
|
||||
for script in scripts:
|
||||
text = script.get_text() or ''
|
||||
if 'frmSave' in text:
|
||||
print("\n" + "="*60)
|
||||
print("frmSave 관련 스크립트:")
|
||||
print("="*60)
|
||||
# frmSave 근처 코드 출력
|
||||
idx = text.find('frmSave')
|
||||
print(text[max(0,idx-100):idx+300])
|
||||
|
||||
await browser.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(analyze())
|
||||
70
backend/find_order_api.py
Normal file
@ -0,0 +1,70 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""주문 확정 API 찾기"""
|
||||
|
||||
import requests
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
import re
|
||||
|
||||
async def find_order_api():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
cookies = await page.context.cookies()
|
||||
await browser.close()
|
||||
|
||||
session = requests.Session()
|
||||
for c in cookies:
|
||||
session.cookies.set(c['name'], c['value'])
|
||||
|
||||
# order.js 다운로드
|
||||
resp = session.get('https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1')
|
||||
content = resp.text
|
||||
|
||||
# InsertOrder, ConfirmOrder, SubmitOrder 등 찾기
|
||||
print("="*60)
|
||||
print("주문 관련 함수 찾기")
|
||||
print("="*60)
|
||||
|
||||
# 함수 찾기
|
||||
funcs = ['InsertOrder', 'ConfirmOrder', 'SubmitOrder', 'SaveOrder', 'ProcessOrder', 'DataOrder']
|
||||
for func in funcs:
|
||||
start = content.find(f'function {func}')
|
||||
if start < 0:
|
||||
start = content.find(f'{func}=function')
|
||||
if start < 0:
|
||||
start = content.find(f'{func}(')
|
||||
|
||||
if start > 0:
|
||||
print(f"\n{func} 발견!")
|
||||
# 함수 내용 출력
|
||||
snippet = content[max(0, start-20):start+800]
|
||||
print(snippet[:600])
|
||||
|
||||
# DataOrder URL 찾기
|
||||
print("\n" + "="*60)
|
||||
print("DataOrder 관련")
|
||||
print("="*60)
|
||||
|
||||
dataorder_pattern = re.findall(r'.{30}DataOrder.{100}', content)
|
||||
for p in dataorder_pattern[:5]:
|
||||
print(p)
|
||||
|
||||
# 모든 ajax URL 찾기
|
||||
print("\n" + "="*60)
|
||||
print("주문 관련 URL")
|
||||
print("="*60)
|
||||
|
||||
urls = re.findall(r'url\s*:\s*["\']([^"\']*(?:Order|Submit|Confirm|Save)[^"\']*)["\']', content, re.IGNORECASE)
|
||||
for url in set(urls):
|
||||
print(url)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(find_order_api())
|
||||
76
backend/find_order_api2.py
Normal file
@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""주문 확정 API 찾기 - 전체 검색"""
|
||||
|
||||
import requests
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
import re
|
||||
|
||||
async def analyze():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
page = await browser.new_page()
|
||||
|
||||
await page.goto('https://gwn.geoweb.kr/Member/Login')
|
||||
await page.fill('input[type="text"]', '7390')
|
||||
await page.fill('input[type="password"]', 'trajet6640')
|
||||
await page.click('button, input[type="submit"]')
|
||||
await page.wait_for_load_state('networkidle')
|
||||
|
||||
cookies = await page.context.cookies()
|
||||
await browser.close()
|
||||
|
||||
session = requests.Session()
|
||||
for c in cookies:
|
||||
session.cookies.set(c['name'], c['value'])
|
||||
|
||||
# 모든 JS 번들 다운로드
|
||||
js_urls = [
|
||||
'https://gwn.geoweb.kr/bundles/order_product_cart?v=JPwFQ8DWaNMW1VmbtWYKTJqxT-5255z351W5iZE1qew1',
|
||||
'https://gwn.geoweb.kr/bundles/order?v=PGhSOAjQ9z6ruAJgJUFuhW9tGQSiJeX6ek-ky3E-tOk1',
|
||||
'https://gwn.geoweb.kr/bundles/javascript?v=Tn_AqbA-PX_uu3d0zjfQOYS6NPSDLtOVqjW95a949Ow1'
|
||||
]
|
||||
|
||||
all_content = ""
|
||||
for url in js_urls:
|
||||
resp = session.get(url)
|
||||
all_content += resp.text + "\n"
|
||||
|
||||
print(f"총 JS 길이: {len(all_content)}")
|
||||
|
||||
# 모든 ajax POST URL 찾기
|
||||
print("\n" + "="*60)
|
||||
print("모든 POST URL:")
|
||||
print("="*60)
|
||||
|
||||
# $.ajax 패턴
|
||||
ajax_patterns = re.findall(r'\$\.ajax\s*\(\s*\{[^}]*url\s*:\s*["\']([^"\']+)["\'][^}]*type\s*:\s*["\']POST["\']', all_content, re.IGNORECASE | re.DOTALL)
|
||||
ajax_patterns += re.findall(r'\$\.ajax\s*\(\s*\{[^}]*type\s*:\s*["\']POST["\'][^}]*url\s*:\s*["\']([^"\']+)["\']', all_content, re.IGNORECASE | re.DOTALL)
|
||||
|
||||
for url in set(ajax_patterns):
|
||||
print(url)
|
||||
|
||||
# 주문저장, 저장 관련
|
||||
print("\n" + "="*60)
|
||||
print("저장/주문 관련 키워드:")
|
||||
print("="*60)
|
||||
|
||||
keywords = ['주문저장', '저장', 'save', 'submit', 'confirm', 'order', 'insert']
|
||||
for kw in keywords:
|
||||
matches = re.findall(rf'.{{50}}{kw}.{{50}}', all_content, re.IGNORECASE)
|
||||
if matches:
|
||||
print(f"\n--- {kw} ---")
|
||||
for m in matches[:3]:
|
||||
print(m.replace('\n', ' ')[:100])
|
||||
|
||||
# 버튼 onclick 찾기
|
||||
print("\n" + "="*60)
|
||||
print("주문저장 버튼:")
|
||||
print("="*60)
|
||||
|
||||
save_btn = re.findall(r'주문저장.{0,200}', all_content)
|
||||
for s in save_btn[:5]:
|
||||
print(s[:150])
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(analyze())
|
||||
BIN
backend/geo_cart_before.png
Normal file
|
After Width: | Height: | Size: 56 KiB |
742
backend/geoyoung_api.py
Normal file
@ -0,0 +1,742 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
지오영 도매상 API - Flask Blueprint
|
||||
|
||||
핵심 로직은 wholesale 패키지에서 가져옴
|
||||
이 파일은 Flask 웹 API 연동만 담당
|
||||
"""
|
||||
|
||||
import re
|
||||
import time
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
# wholesale 패키지 경로 설정
|
||||
import wholesale_path
|
||||
|
||||
# wholesale 패키지에서 핵심 클래스 가져오기
|
||||
from wholesale import GeoYoungSession
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Blueprint 생성
|
||||
geoyoung_bp = Blueprint('geoyoung', __name__, url_prefix='/api/geoyoung')
|
||||
|
||||
|
||||
# ========== 세션 관리 ==========
|
||||
|
||||
_geo_session = None
|
||||
|
||||
def get_geo_session():
|
||||
global _geo_session
|
||||
if _geo_session is None:
|
||||
_geo_session = GeoYoungSession()
|
||||
return _geo_session
|
||||
|
||||
|
||||
def search_geoyoung_stock(keyword: str, include_price: bool = True):
|
||||
"""지오영 재고 검색 (동기, 단가 포함)"""
|
||||
try:
|
||||
session = get_geo_session()
|
||||
|
||||
# 새 API 사용 (단가 포함)
|
||||
result = session.search_products(keyword, include_price=include_price)
|
||||
|
||||
if result.get('success'):
|
||||
# 기존 형식으로 변환
|
||||
items = [{
|
||||
'insurance_code': item['code'],
|
||||
'internal_code': item.get('internal_code'),
|
||||
'manufacturer': item['manufacturer'],
|
||||
'product_name': item['name'],
|
||||
'specification': item['spec'],
|
||||
'stock': item['stock'],
|
||||
'price': item.get('price', 0), # 단가 추가!
|
||||
'box_qty': item.get('box_qty'),
|
||||
'case_qty': item.get('case_qty')
|
||||
} for item in result['items']]
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'keyword': keyword,
|
||||
'count': len(items),
|
||||
'items': items
|
||||
}
|
||||
else:
|
||||
return {'success': False, 'error': result.get('error'), 'message': '검색 실패'}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 검색 오류: {e}")
|
||||
return {'success': False, 'error': 'SEARCH_ERROR', 'message': str(e)}
|
||||
|
||||
|
||||
# ========== Flask API Routes ==========
|
||||
|
||||
@geoyoung_bp.route('/stock', methods=['GET'])
|
||||
def api_geoyoung_stock():
|
||||
"""
|
||||
지오영 재고 조회 API (빠름)
|
||||
|
||||
GET /api/geoyoung/stock?kd_code=670400830
|
||||
GET /api/geoyoung/stock?keyword=레바미피드
|
||||
"""
|
||||
kd_code = request.args.get('kd_code', '').strip()
|
||||
keyword = request.args.get('keyword', '').strip()
|
||||
|
||||
search_term = kd_code or keyword
|
||||
|
||||
if not search_term:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'kd_code 또는 keyword 파라미터가 필요합니다'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
result = search_geoyoung_stock(search_term)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 API 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/stock-by-name', methods=['GET'])
|
||||
def api_geoyoung_stock_by_name():
|
||||
"""
|
||||
제품명에서 성분명 추출 후 지오영 검색
|
||||
|
||||
GET /api/geoyoung/stock-by-name?product_name=휴니즈레바미피드정_(0.1g/1정)
|
||||
"""
|
||||
product_name = request.args.get('product_name', '').strip()
|
||||
|
||||
if not product_name:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'product_name 파라미터가 필요합니다'
|
||||
}), 400
|
||||
|
||||
# 성분명 추출
|
||||
prefixes = ['휴니즈', '휴온스', '대웅', '한미', '종근당', '유한', '녹십자', '동아', '일동', '광동',
|
||||
'삼성', '안국', '보령', '광동', '경동', '현대', '일양', '태극', '환인', '에스케이']
|
||||
ingredient = product_name
|
||||
|
||||
for prefix in prefixes:
|
||||
if ingredient.startswith(prefix):
|
||||
ingredient = ingredient[len(prefix):]
|
||||
break
|
||||
|
||||
match = re.match(r'^([가-힣a-zA-Z]+)', ingredient)
|
||||
if match:
|
||||
ingredient = match.group(1)
|
||||
if ingredient.endswith('정'):
|
||||
ingredient = ingredient[:-1]
|
||||
elif ingredient.endswith('캡슐'):
|
||||
ingredient = ingredient[:-2]
|
||||
|
||||
if not ingredient:
|
||||
ingredient = product_name[:10]
|
||||
|
||||
try:
|
||||
result = search_geoyoung_stock(ingredient)
|
||||
result['extracted_ingredient'] = ingredient
|
||||
result['original_product_name'] = product_name
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 API 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/session-status', methods=['GET'])
|
||||
def api_session_status():
|
||||
"""세션 상태 확인"""
|
||||
session = get_geo_session()
|
||||
return jsonify({
|
||||
'logged_in': session._logged_in,
|
||||
'last_login': session._last_login,
|
||||
'session_age_sec': int(time.time() - session._last_login) if session._last_login else None
|
||||
})
|
||||
|
||||
|
||||
@geoyoung_bp.route('/cart', methods=['GET'])
|
||||
def api_geoyoung_cart():
|
||||
"""장바구니 조회 API"""
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.get_cart()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e), 'items': []}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/cart/clear', methods=['POST'])
|
||||
def api_geoyoung_cart_clear():
|
||||
"""장바구니 비우기 API"""
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.clear_cart()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/cart/cancel', methods=['POST'])
|
||||
def api_geoyoung_cart_cancel():
|
||||
"""
|
||||
장바구니 개별 항목 삭제 API (Hard delete)
|
||||
|
||||
POST /api/geoyoung/cart/cancel
|
||||
{
|
||||
"row_index": 0, // 또는
|
||||
"product_code": "008709"
|
||||
}
|
||||
|
||||
⚠️ 지오영은 완전 삭제됨 (복원 불가, 다시 추가해야 함)
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
row_index = data.get('row_index')
|
||||
product_code = data.get('product_code')
|
||||
|
||||
if row_index is None and not product_code:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'row_index 또는 product_code 필요'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.cancel_item(row_index=row_index, product_code=product_code)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/cart/restore', methods=['POST'])
|
||||
def api_geoyoung_cart_restore():
|
||||
"""
|
||||
삭제된 항목 복원 API - 지오영은 Hard delete이므로 지원 안 함
|
||||
|
||||
Returns:
|
||||
항상 {'success': False, 'error': 'NOT_SUPPORTED'}
|
||||
"""
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'NOT_SUPPORTED',
|
||||
'message': '지오영은 삭제 후 복원 불가 (다시 추가 필요)'
|
||||
}), 400
|
||||
|
||||
|
||||
@geoyoung_bp.route('/confirm', methods=['POST'])
|
||||
def api_geoyoung_confirm():
|
||||
"""주문 확정 API"""
|
||||
data = request.get_json() or {}
|
||||
memo = data.get('memo', '')
|
||||
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.submit_order(memo)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/full-order', methods=['POST'])
|
||||
def api_geoyoung_full_order():
|
||||
"""전체 주문 API (검색 → 장바구니 → 확정)"""
|
||||
data = request.get_json()
|
||||
|
||||
if not data or not data.get('kd_code'):
|
||||
return jsonify({'success': False, 'error': 'kd_code required'}), 400
|
||||
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.full_order(
|
||||
kd_code=data['kd_code'],
|
||||
quantity=data.get('quantity', 1),
|
||||
specification=data.get('specification'),
|
||||
check_stock=data.get('check_stock', True),
|
||||
auto_confirm=data.get('auto_confirm', True),
|
||||
memo=data.get('memo', '')
|
||||
)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/order', methods=['POST'])
|
||||
def api_geoyoung_order():
|
||||
"""지오영 주문 API (장바구니 추가)"""
|
||||
data = request.get_json()
|
||||
|
||||
if not data:
|
||||
return jsonify({'success': False, 'error': 'NO_DATA'}), 400
|
||||
|
||||
kd_code = data.get('kd_code', '').strip()
|
||||
quantity = data.get('quantity', 1)
|
||||
specification = data.get('specification')
|
||||
check_stock = data.get('check_stock', True)
|
||||
|
||||
if not kd_code:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'kd_code가 필요합니다'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.quick_order(
|
||||
kd_code=kd_code,
|
||||
quantity=quantity,
|
||||
spec=specification,
|
||||
check_stock=check_stock
|
||||
)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 주문 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'ORDER_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/order-batch', methods=['POST'])
|
||||
def api_geoyoung_order_batch():
|
||||
"""지오영 일괄 주문 API"""
|
||||
data = request.get_json()
|
||||
|
||||
if not data or not data.get('items'):
|
||||
return jsonify({'success': False, 'error': 'NO_ITEMS'}), 400
|
||||
|
||||
items = data.get('items', [])
|
||||
check_stock = data.get('check_stock', True)
|
||||
|
||||
session = get_geo_session()
|
||||
results = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
|
||||
for item in items:
|
||||
kd_code = item.get('kd_code', '').strip()
|
||||
quantity = item.get('quantity', 1)
|
||||
specification = item.get('specification')
|
||||
|
||||
if not kd_code:
|
||||
results.append({
|
||||
'kd_code': kd_code,
|
||||
'success': False,
|
||||
'error': 'MISSING_KD_CODE'
|
||||
})
|
||||
failed_count += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
result = session.quick_order(
|
||||
kd_code=kd_code,
|
||||
quantity=quantity,
|
||||
spec=specification,
|
||||
check_stock=check_stock
|
||||
)
|
||||
result['kd_code'] = kd_code
|
||||
result['requested_qty'] = quantity
|
||||
results.append(result)
|
||||
|
||||
if result.get('success'):
|
||||
success_count += 1
|
||||
else:
|
||||
failed_count += 1
|
||||
|
||||
except Exception as e:
|
||||
results.append({
|
||||
'kd_code': kd_code,
|
||||
'success': False,
|
||||
'error': 'EXCEPTION',
|
||||
'message': str(e)
|
||||
})
|
||||
failed_count += 1
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'total': len(items),
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'results': results
|
||||
})
|
||||
|
||||
|
||||
# ========== 잔고 탐색 (임시) ==========
|
||||
|
||||
@geoyoung_bp.route('/explore-balance', methods=['GET'])
|
||||
def api_explore_balance():
|
||||
"""잔고 페이지 탐색 (임시 디버그용)"""
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
session = get_geo_session()
|
||||
if not session._logged_in:
|
||||
session.login()
|
||||
|
||||
results = {
|
||||
'logged_in': session._logged_in,
|
||||
'cookies': len(session.session.cookies),
|
||||
'pages_found': [],
|
||||
'balance_pages': []
|
||||
}
|
||||
|
||||
# Order 페이지에서 메뉴 링크 수집
|
||||
try:
|
||||
# 먼저 Order 페이지 접근
|
||||
resp = session.session.get(f"{session.BASE_URL}/Home/Order", timeout=10)
|
||||
results['order_page'] = {
|
||||
'status': resp.status_code,
|
||||
'url': resp.url,
|
||||
'is_error': 'Error' in resp.url
|
||||
}
|
||||
|
||||
if resp.status_code == 200 and 'Error' not in resp.url:
|
||||
soup = BeautifulSoup(resp.text, 'html.parser')
|
||||
|
||||
# 모든 링크 추출
|
||||
for link in soup.find_all('a', href=True):
|
||||
href = link.get('href', '')
|
||||
text = link.get_text(strip=True)[:50]
|
||||
|
||||
if href.startswith('/') and href not in [l['href'] for l in results['pages_found']]:
|
||||
entry = {'href': href, 'text': text}
|
||||
results['pages_found'].append(entry)
|
||||
|
||||
# 잔고 관련 키워드
|
||||
keywords = ['account', 'balance', 'trans', 'state', 'history', 'ledger', '잔고', '잔액', '거래', '명세', '내역']
|
||||
if any(kw in href.lower() or kw in text for kw in keywords):
|
||||
results['balance_pages'].append(entry)
|
||||
|
||||
except Exception as e:
|
||||
results['error'] = str(e)
|
||||
|
||||
return jsonify(results)
|
||||
|
||||
|
||||
@geoyoung_bp.route('/balance', methods=['GET'])
|
||||
def api_get_balance():
|
||||
"""
|
||||
잔고액 조회
|
||||
|
||||
GET /api/geoyoung/balance
|
||||
"""
|
||||
session = get_geo_session()
|
||||
|
||||
# get_balance 메서드가 있으면 호출
|
||||
if hasattr(session, 'get_balance'):
|
||||
result = session.get_balance()
|
||||
return jsonify(result)
|
||||
else:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'NOT_IMPLEMENTED',
|
||||
'message': '지오영 잔고 조회 미구현'
|
||||
}), 501
|
||||
|
||||
|
||||
@geoyoung_bp.route('/monthly-sales', methods=['GET'])
|
||||
def api_get_monthly_sales():
|
||||
"""
|
||||
월간 매출 조회
|
||||
|
||||
GET /api/geoyoung/monthly-sales?year=2026&month=3
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
year = request.args.get('year', type=int)
|
||||
month = request.args.get('month', type=int)
|
||||
|
||||
# 기본값: 현재 월
|
||||
if not year or not month:
|
||||
now = datetime.now()
|
||||
year = year or now.year
|
||||
month = month or now.month
|
||||
|
||||
session = get_geo_session()
|
||||
|
||||
if hasattr(session, 'get_monthly_sales'):
|
||||
result = session.get_monthly_sales(year, month)
|
||||
return jsonify(result)
|
||||
else:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'NOT_IMPLEMENTED',
|
||||
'message': '지오영 월간 매출 조회 미구현'
|
||||
}), 501
|
||||
|
||||
|
||||
# ========== 주문 조회 API ==========
|
||||
|
||||
@geoyoung_bp.route('/order-list', methods=['GET'])
|
||||
def api_geoyoung_order_list():
|
||||
"""
|
||||
지오영 주문 목록 조회 API
|
||||
|
||||
GET /api/geoyoung/order-list?start_date=2026-03-01&end_date=2026-03-07
|
||||
|
||||
Query Parameters:
|
||||
start_date: 시작일 (YYYY-MM-DD), 기본값 30일 전
|
||||
end_date: 종료일 (YYYY-MM-DD), 기본값 오늘
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"orders": [{
|
||||
"order_num": "DA2603-0006409",
|
||||
"order_date": "2026-03-07",
|
||||
"order_time": "09:08:55",
|
||||
"total_amount": 132020,
|
||||
"item_count": 3,
|
||||
"status": "출고확정"
|
||||
}, ...],
|
||||
"total_count": 5,
|
||||
"start_date": "2026-03-01",
|
||||
"end_date": "2026-03-07"
|
||||
}
|
||||
"""
|
||||
start_date = request.args.get('start_date', '').strip()
|
||||
end_date = request.args.get('end_date', '').strip()
|
||||
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.get_order_list(start_date or None, end_date or None)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 주문 목록 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e),
|
||||
'orders': [],
|
||||
'total_count': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/order-detail/<order_num>', methods=['GET'])
|
||||
def api_geoyoung_order_detail(order_num):
|
||||
"""
|
||||
지오영 주문 상세 조회 API
|
||||
|
||||
GET /api/geoyoung/order-detail/DA2603-0006409
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"order_num": "DA2603-0006409",
|
||||
"order_date": "2026-03-07",
|
||||
"order_time": "09:08:55",
|
||||
"items": [{
|
||||
"product_code": "008709",
|
||||
"kd_code": "670400830",
|
||||
"product_name": "레바미피드정100mg",
|
||||
"spec": "100mg",
|
||||
"quantity": 10,
|
||||
"unit_price": 500,
|
||||
"amount": 5000
|
||||
}, ...],
|
||||
"total_amount": 132020,
|
||||
"item_count": 3
|
||||
}
|
||||
"""
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.get_order_detail(order_num)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 주문 상세 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e),
|
||||
'order_num': order_num,
|
||||
'items': [],
|
||||
'total_amount': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/orders/summary-by-kd', methods=['GET'])
|
||||
def api_geoyoung_orders_by_kd():
|
||||
"""
|
||||
지오영 주문량 KD코드별 집계 API
|
||||
|
||||
GET /api/geoyoung/orders/summary-by-kd?start_date=2026-03-01&end_date=2026-03-07
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"order_count": 4,
|
||||
"by_kd_code": {
|
||||
"670400830": {
|
||||
"product_name": "레바미피드정",
|
||||
"spec": "100T",
|
||||
"boxes": 2,
|
||||
"units": 200
|
||||
}
|
||||
},
|
||||
"total_products": 15
|
||||
}
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
start_date = request.args.get('start_date', today).strip()
|
||||
end_date = request.args.get('end_date', today).strip()
|
||||
|
||||
def parse_spec(spec: str, product_name: str = '') -> int:
|
||||
"""
|
||||
규격에서 수량 추출 (30T → 30, 100C → 100)
|
||||
|
||||
단위 처리:
|
||||
- T/C/P: 정/캡슐/포 → 숫자 그대로 (30T → 30)
|
||||
- D: 도즈/분사 → 1로 처리 (140D → 1, 박스 단위)
|
||||
- mg/ml/g: 용량 → 1로 처리
|
||||
"""
|
||||
combined = f"{spec} {product_name}"
|
||||
|
||||
# D(도즈) 단위는 박스 단위로 계산 (140D → 1)
|
||||
if re.search(r'\d+\s*D\b', combined, re.IGNORECASE):
|
||||
return 1
|
||||
|
||||
# T/C/P 단위가 붙은 숫자 추출 (예: 14T, 100C, 30P)
|
||||
qty_match = re.search(r'(\d+)\s*[TCP]\b', combined, re.IGNORECASE)
|
||||
if qty_match:
|
||||
return int(qty_match.group(1))
|
||||
|
||||
# 없으면 spec의 첫 번째 숫자 (mg, ml 등 용량일 수 있음 - 기본값 1)
|
||||
if spec:
|
||||
num_match = re.search(r'(\d+)', spec)
|
||||
if num_match:
|
||||
val = int(num_match.group(1))
|
||||
# mg, ml 같은 용량 단위면 수량 1로 처리
|
||||
if re.search(r'\d+\s*(mg|ml|g)\b', spec, re.IGNORECASE):
|
||||
return 1
|
||||
return val
|
||||
|
||||
return 1
|
||||
|
||||
try:
|
||||
session = get_geo_session()
|
||||
|
||||
# 주문 목록 조회 (items 포함)
|
||||
orders_result = session.get_order_list(start_date, end_date)
|
||||
|
||||
if not orders_result.get('success'):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': orders_result.get('error', 'ORDERS_FETCH_FAILED'),
|
||||
'by_kd_code': {},
|
||||
'order_count': 0
|
||||
})
|
||||
|
||||
orders = orders_result.get('orders', [])
|
||||
|
||||
# 각 주문의 items에 KD코드 추가 (enrich)
|
||||
for order in orders:
|
||||
items = order.get('items', [])
|
||||
if items:
|
||||
session._enrich_kd_codes(items)
|
||||
|
||||
# KD코드별 집계
|
||||
kd_summary = {}
|
||||
|
||||
for order in orders:
|
||||
# 지오영은 get_order_list에서 items도 같이 반환
|
||||
for item in order.get('items', []):
|
||||
# 취소/삭제 상태 제외
|
||||
status = item.get('status', '').strip()
|
||||
if '취소' in status or '삭제' in status:
|
||||
continue
|
||||
|
||||
kd_code = item.get('kd_code', '')
|
||||
if not kd_code:
|
||||
continue
|
||||
|
||||
product_name = item.get('product_name', '')
|
||||
spec = item.get('spec', '')
|
||||
quantity = item.get('quantity', 0) or item.get('order_qty', 0)
|
||||
per_unit = parse_spec(spec, product_name)
|
||||
total_units = quantity * per_unit
|
||||
|
||||
if kd_code not in kd_summary:
|
||||
kd_summary[kd_code] = {
|
||||
'product_name': product_name,
|
||||
'spec': spec,
|
||||
'boxes': 0,
|
||||
'units': 0
|
||||
}
|
||||
|
||||
kd_summary[kd_code]['boxes'] += quantity
|
||||
kd_summary[kd_code]['units'] += total_units
|
||||
|
||||
logger.info(f"지오영 주문량 집계: {start_date}~{end_date}, {len(orders)}건 주문, {len(kd_summary)}개 품목")
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'order_count': len(orders),
|
||||
'period': {'start': start_date, 'end': end_date},
|
||||
'by_kd_code': kd_summary,
|
||||
'total_products': len(kd_summary)
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 주문량 집계 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e),
|
||||
'by_kd_code': {},
|
||||
'order_count': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@geoyoung_bp.route('/order-today', methods=['GET'])
|
||||
def api_geoyoung_order_today():
|
||||
"""
|
||||
지오영 오늘 주문 요약 API
|
||||
|
||||
GET /api/geoyoung/order-today
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"date": "2026-03-07",
|
||||
"order_count": 3,
|
||||
"total_amount": 450000,
|
||||
"item_count": 15,
|
||||
"orders": [...]
|
||||
}
|
||||
"""
|
||||
try:
|
||||
session = get_geo_session()
|
||||
result = session.get_today_order_summary()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"지오영 오늘 주문 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e),
|
||||
'date': '',
|
||||
'order_count': 0,
|
||||
'total_amount': 0
|
||||
}), 500
|
||||
|
||||
|
||||
# ========== 하위 호환성 ==========
|
||||
|
||||
# 기존 코드에서 직접 클래스 참조하는 경우를 위해
|
||||
GeoyoungSession = GeoYoungSession
|
||||
10
backend/ordLedger_page.html
Normal file
BIN
backend/ordLedger_screenshot.png
Normal file
|
After Width: | Height: | Size: 302 KiB |
1616
backend/order_api.py
Normal file
861
backend/order_db.py
Normal file
@ -0,0 +1,861 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
주문 관리 DB (SQLite)
|
||||
- 다중 도매상 지원 (지오영, 수인, 백제 등)
|
||||
- 주문 상태 추적
|
||||
- 품목별 결과 관리
|
||||
- 자동화 ERP 확장 대비
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Optional, List, Dict
|
||||
import json
|
||||
|
||||
# DB 경로
|
||||
DB_PATH = os.path.join(os.path.dirname(__file__), 'db', 'orders.db')
|
||||
|
||||
|
||||
def get_connection():
|
||||
"""DB 연결"""
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def init_db():
|
||||
"""DB 초기화 - 테이블 생성"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 도매상 마스터
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS wholesalers (
|
||||
id TEXT PRIMARY KEY, -- 'geoyoung', 'sooin', 'baekje'
|
||||
name TEXT NOT NULL, -- '지오영', '수인', '백제'
|
||||
api_type TEXT, -- 'playwright', 'api', 'manual'
|
||||
base_url TEXT,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
config_json TEXT, -- 로그인 정보 등 (암호화 권장)
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
''')
|
||||
|
||||
# 기본 도매상 등록
|
||||
cursor.execute('''
|
||||
INSERT OR IGNORE INTO wholesalers (id, name, api_type, base_url)
|
||||
VALUES
|
||||
('geoyoung', '지오영', 'playwright', 'https://gwn.geoweb.kr'),
|
||||
('sooin', '수인', 'manual', NULL),
|
||||
('baekje', '백제', 'manual', NULL)
|
||||
''')
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 주문 헤더
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
order_no TEXT UNIQUE, -- 주문번호 (ORD-20260306-001)
|
||||
wholesaler_id TEXT NOT NULL, -- 도매상 ID
|
||||
|
||||
-- 주문 정보
|
||||
order_date TEXT NOT NULL, -- 주문일 (YYYY-MM-DD)
|
||||
order_time TEXT, -- 주문시간 (HH:MM:SS)
|
||||
order_type TEXT DEFAULT 'manual', -- 'manual', 'auto', 'scheduled'
|
||||
order_session TEXT, -- 'morning', 'afternoon', 'evening'
|
||||
|
||||
-- 상태
|
||||
status TEXT DEFAULT 'draft', -- draft, pending, submitted, partial, completed, failed, cancelled
|
||||
|
||||
-- 집계
|
||||
total_items INTEGER DEFAULT 0,
|
||||
total_qty INTEGER DEFAULT 0,
|
||||
success_items INTEGER DEFAULT 0,
|
||||
failed_items INTEGER DEFAULT 0,
|
||||
|
||||
-- 참조
|
||||
parent_order_id INTEGER, -- 재주문 시 원주문 참조
|
||||
reference_period TEXT, -- 사용량 조회 기간 (2026-03-01~2026-03-06)
|
||||
|
||||
-- 메타
|
||||
note TEXT,
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
submitted_at TEXT, -- 실제 제출 시간
|
||||
completed_at TEXT,
|
||||
|
||||
FOREIGN KEY (wholesaler_id) REFERENCES wholesalers(id),
|
||||
FOREIGN KEY (parent_order_id) REFERENCES orders(id)
|
||||
)
|
||||
''')
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 주문 품목 상세
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS order_items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
order_id INTEGER NOT NULL,
|
||||
|
||||
-- 약품 정보
|
||||
drug_code TEXT NOT NULL, -- PIT3000 약품코드
|
||||
kd_code TEXT, -- 보험코드 (지오영 검색용)
|
||||
internal_code TEXT, -- 🔧 도매상 내부 코드 (장바구니 직접 추가용!)
|
||||
product_name TEXT NOT NULL,
|
||||
manufacturer TEXT,
|
||||
|
||||
-- 규격/수량
|
||||
specification TEXT, -- '30T', '300T', '500T'
|
||||
unit_qty INTEGER, -- 규격당 수량 (30, 300, 500)
|
||||
order_qty INTEGER NOT NULL, -- 주문 수량 (단위 개수)
|
||||
total_dose INTEGER, -- 총 정제수 (order_qty * unit_qty)
|
||||
|
||||
-- 주문 근거
|
||||
usage_qty INTEGER, -- 사용량 (조회 기간)
|
||||
current_stock INTEGER, -- 주문 시점 재고
|
||||
|
||||
-- 가격 (선택)
|
||||
unit_price INTEGER,
|
||||
total_price INTEGER,
|
||||
|
||||
-- 상태
|
||||
status TEXT DEFAULT 'pending', -- pending, submitted, success, failed, cancelled
|
||||
|
||||
-- 결과
|
||||
result_code TEXT, -- 'OK', 'OUT_OF_STOCK', 'NOT_FOUND', 'ERROR'
|
||||
result_message TEXT,
|
||||
wholesaler_order_no TEXT, -- 도매상 측 주문번호
|
||||
|
||||
-- 메타
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
|
||||
)
|
||||
''')
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 주문 로그 (상태 변경 이력)
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS order_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
order_id INTEGER NOT NULL,
|
||||
order_item_id INTEGER, -- NULL이면 주문 전체 로그
|
||||
|
||||
action TEXT NOT NULL, -- 'created', 'submitted', 'success', 'failed', 'cancelled'
|
||||
old_status TEXT,
|
||||
new_status TEXT,
|
||||
|
||||
message TEXT,
|
||||
detail_json TEXT, -- API 응답 등 상세 정보
|
||||
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (order_item_id) REFERENCES order_items(id) ON DELETE CASCADE
|
||||
)
|
||||
''')
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 주문 컨텍스트 (AI 학습용 스냅샷)
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS order_context (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
order_item_id INTEGER NOT NULL,
|
||||
|
||||
-- 약품 정보
|
||||
drug_code TEXT NOT NULL,
|
||||
product_name TEXT,
|
||||
|
||||
-- 주문 시점 재고
|
||||
stock_at_order INTEGER, -- 주문 시점 현재고
|
||||
|
||||
-- 사용량 분석
|
||||
usage_1d INTEGER, -- 최근 1일 사용량
|
||||
usage_7d INTEGER, -- 최근 7일 사용량
|
||||
usage_30d INTEGER, -- 최근 30일 사용량
|
||||
avg_daily_usage REAL, -- 일평균 사용량 (30일 기준)
|
||||
|
||||
-- 주문 패턴
|
||||
ordered_spec TEXT, -- 주문한 규격 (30T, 300T)
|
||||
ordered_qty INTEGER, -- 주문 수량 (단위 개수)
|
||||
ordered_dose INTEGER, -- 주문 총 정제수
|
||||
|
||||
-- 규격 선택 이유 (AI 분석용)
|
||||
available_specs TEXT, -- 가능한 규격들 JSON ["30T", "300T"]
|
||||
spec_stocks TEXT, -- 규격별 도매상 재고 JSON {"30T": 50, "300T": 0}
|
||||
selection_reason TEXT, -- 'stock_available', 'best_fit', 'only_option', 'user_choice'
|
||||
|
||||
-- 예측 vs 실제 (나중에 업데이트)
|
||||
days_until_stockout REAL, -- 주문 시점 예상 재고 소진일
|
||||
actual_reorder_days INTEGER, -- 실제 재주문까지 일수 (나중에 업데이트)
|
||||
|
||||
-- 메타
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
FOREIGN KEY (order_item_id) REFERENCES order_items(id) ON DELETE CASCADE
|
||||
)
|
||||
''')
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 일별 사용량 추적 (시계열 데이터)
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS daily_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
drug_code TEXT NOT NULL,
|
||||
usage_date TEXT NOT NULL, -- YYYY-MM-DD
|
||||
|
||||
-- 처방 데이터
|
||||
rx_count INTEGER DEFAULT 0, -- 처방 건수
|
||||
rx_qty INTEGER DEFAULT 0, -- 처방 수량 (정제수)
|
||||
|
||||
-- POS 데이터 (일반약)
|
||||
pos_count INTEGER DEFAULT 0,
|
||||
pos_qty INTEGER DEFAULT 0,
|
||||
|
||||
-- 집계
|
||||
total_qty INTEGER DEFAULT 0,
|
||||
|
||||
-- 재고 스냅샷
|
||||
stock_start INTEGER, -- 시작 재고
|
||||
stock_end INTEGER, -- 종료 재고
|
||||
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
UNIQUE(drug_code, usage_date)
|
||||
)
|
||||
''')
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# AI 분석 결과/패턴
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS order_patterns (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
drug_code TEXT NOT NULL,
|
||||
|
||||
-- 분석 기간
|
||||
analysis_date TEXT NOT NULL,
|
||||
analysis_period_days INTEGER,
|
||||
|
||||
-- 사용 패턴
|
||||
avg_daily_usage REAL,
|
||||
usage_stddev REAL, -- 사용량 표준편차 (변동성)
|
||||
peak_usage INTEGER, -- 최대 사용량
|
||||
|
||||
-- 주문 패턴
|
||||
typical_order_spec TEXT, -- 주로 주문하는 규격
|
||||
typical_order_qty INTEGER, -- 주로 주문하는 수량
|
||||
order_frequency_days REAL, -- 평균 주문 주기 (일)
|
||||
|
||||
-- AI 추천
|
||||
recommended_spec TEXT, -- 추천 규격
|
||||
recommended_qty INTEGER, -- 추천 수량
|
||||
recommended_reorder_point INTEGER,-- 추천 재주문점 (재고가 이 이하면 주문)
|
||||
confidence_score REAL, -- 추천 신뢰도 (0-1)
|
||||
|
||||
-- 모델 정보
|
||||
model_version TEXT,
|
||||
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
UNIQUE(drug_code, analysis_date)
|
||||
)
|
||||
''')
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 인덱스
|
||||
# ─────────────────────────────────────────────
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_orders_date ON orders(order_date)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_orders_wholesaler ON orders(wholesaler_id)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_order_items_drug ON order_items(drug_code)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_order_items_status ON order_items(status)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_order_context_drug ON order_context(drug_code)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_daily_usage_drug ON daily_usage(drug_code)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_daily_usage_date ON daily_usage(usage_date)')
|
||||
cursor.execute('CREATE INDEX IF NOT EXISTS idx_order_patterns_drug ON order_patterns(drug_code)')
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def generate_order_no(wholesaler_id: str) -> str:
|
||||
"""주문번호 생성 (ORD-GEO-20260306-001)"""
|
||||
prefix_map = {
|
||||
'geoyoung': 'GEO',
|
||||
'sooin': 'SOO',
|
||||
'baekje': 'BAK'
|
||||
}
|
||||
prefix = prefix_map.get(wholesaler_id, 'ORD')
|
||||
date_str = datetime.now().strftime('%Y%m%d')
|
||||
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 오늘 해당 도매상 주문 수 카운트
|
||||
cursor.execute('''
|
||||
SELECT COUNT(*) FROM orders
|
||||
WHERE wholesaler_id = ? AND order_date = ?
|
||||
''', (wholesaler_id, datetime.now().strftime('%Y-%m-%d')))
|
||||
|
||||
count = cursor.fetchone()[0] + 1
|
||||
conn.close()
|
||||
|
||||
return f"ORD-{prefix}-{date_str}-{count:03d}"
|
||||
|
||||
|
||||
def create_order(wholesaler_id: str, items: List[Dict],
|
||||
order_type: str = 'manual',
|
||||
order_session: str = None,
|
||||
reference_period: str = None,
|
||||
note: str = None) -> Dict:
|
||||
"""
|
||||
주문 생성 (draft 상태)
|
||||
|
||||
items: [
|
||||
{
|
||||
'drug_code': '670400830',
|
||||
'kd_code': '670400830',
|
||||
'product_name': '레바미피드정 30T',
|
||||
'manufacturer': '휴온스',
|
||||
'specification': '30T',
|
||||
'unit_qty': 30,
|
||||
'order_qty': 10,
|
||||
'usage_qty': 280,
|
||||
'current_stock': 50
|
||||
}
|
||||
]
|
||||
"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
order_no = generate_order_no(wholesaler_id)
|
||||
now = datetime.now()
|
||||
|
||||
# 주문 헤더 생성
|
||||
cursor.execute('''
|
||||
INSERT INTO orders (
|
||||
order_no, wholesaler_id, order_date, order_time,
|
||||
order_type, order_session, reference_period, note,
|
||||
total_items, total_qty, status
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft')
|
||||
''', (
|
||||
order_no,
|
||||
wholesaler_id,
|
||||
now.strftime('%Y-%m-%d'),
|
||||
now.strftime('%H:%M:%S'),
|
||||
order_type,
|
||||
order_session,
|
||||
reference_period,
|
||||
note,
|
||||
len(items),
|
||||
sum(item.get('order_qty', 0) for item in items)
|
||||
))
|
||||
|
||||
order_id = cursor.lastrowid
|
||||
|
||||
# 주문 품목 생성
|
||||
for item in items:
|
||||
unit_qty = item.get('unit_qty', 1)
|
||||
order_qty = item.get('order_qty', 0)
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO order_items (
|
||||
order_id, drug_code, kd_code, internal_code, product_name, manufacturer,
|
||||
specification, unit_qty, order_qty, total_dose,
|
||||
usage_qty, current_stock, status
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
|
||||
''', (
|
||||
order_id,
|
||||
item.get('drug_code'),
|
||||
item.get('kd_code'),
|
||||
item.get('internal_code'), # 🔧 도매상 내부 코드 저장!
|
||||
item.get('product_name'),
|
||||
item.get('manufacturer'),
|
||||
item.get('specification'),
|
||||
unit_qty,
|
||||
order_qty,
|
||||
order_qty * unit_qty,
|
||||
item.get('usage_qty'),
|
||||
item.get('current_stock')
|
||||
))
|
||||
|
||||
# 로그
|
||||
cursor.execute('''
|
||||
INSERT INTO order_logs (order_id, action, new_status, message)
|
||||
VALUES (?, 'created', 'draft', ?)
|
||||
''', (order_id, f'{len(items)}개 품목 주문 생성'))
|
||||
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'order_id': order_id,
|
||||
'order_no': order_no,
|
||||
'total_items': len(items)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
return {'success': False, 'error': str(e)}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_order(order_id: int) -> Optional[Dict]:
|
||||
"""주문 조회 (품목 포함)"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('SELECT * FROM orders WHERE id = ?', (order_id,))
|
||||
order = cursor.fetchone()
|
||||
|
||||
if not order:
|
||||
conn.close()
|
||||
return None
|
||||
|
||||
cursor.execute('SELECT * FROM order_items WHERE order_id = ?', (order_id,))
|
||||
items = cursor.fetchall()
|
||||
|
||||
conn.close()
|
||||
|
||||
return {
|
||||
**dict(order),
|
||||
'items': [dict(item) for item in items]
|
||||
}
|
||||
|
||||
|
||||
def update_order_status(order_id: int, status: str, message: str = None) -> bool:
|
||||
"""주문 상태 업데이트"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
# 현재 상태 조회
|
||||
cursor.execute('SELECT status FROM orders WHERE id = ?', (order_id,))
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
|
||||
old_status = row['status']
|
||||
|
||||
# 상태 업데이트
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
update_fields = ['status = ?', 'updated_at = ?']
|
||||
params = [status, now]
|
||||
|
||||
if status == 'submitted':
|
||||
update_fields.append('submitted_at = ?')
|
||||
params.append(now)
|
||||
elif status in ('completed', 'failed'):
|
||||
update_fields.append('completed_at = ?')
|
||||
params.append(now)
|
||||
|
||||
params.append(order_id)
|
||||
|
||||
cursor.execute(f'''
|
||||
UPDATE orders SET {', '.join(update_fields)} WHERE id = ?
|
||||
''', params)
|
||||
|
||||
# 로그
|
||||
cursor.execute('''
|
||||
INSERT INTO order_logs (order_id, action, old_status, new_status, message)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
''', (order_id, status, old_status, status, message))
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_item_result(item_id: int, status: str, result_code: str = None,
|
||||
result_message: str = None, wholesaler_order_no: str = None) -> bool:
|
||||
"""품목 결과 업데이트"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
cursor.execute('''
|
||||
UPDATE order_items SET
|
||||
status = ?,
|
||||
result_code = ?,
|
||||
result_message = ?,
|
||||
wholesaler_order_no = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
''', (status, result_code, result_message, wholesaler_order_no, item_id))
|
||||
|
||||
# 주문 집계 업데이트
|
||||
cursor.execute('SELECT order_id FROM order_items WHERE id = ?', (item_id,))
|
||||
order_id = cursor.fetchone()['order_id']
|
||||
|
||||
cursor.execute('''
|
||||
UPDATE orders SET
|
||||
success_items = (SELECT COUNT(*) FROM order_items WHERE order_id = ? AND status = 'success'),
|
||||
failed_items = (SELECT COUNT(*) FROM order_items WHERE order_id = ? AND status = 'failed'),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
''', (order_id, order_id, order_id))
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_order_history(wholesaler_id: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
status: str = None,
|
||||
limit: int = 50) -> List[Dict]:
|
||||
"""주문 이력 조회"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
query = 'SELECT * FROM orders WHERE 1=1'
|
||||
params = []
|
||||
|
||||
if wholesaler_id:
|
||||
query += ' AND wholesaler_id = ?'
|
||||
params.append(wholesaler_id)
|
||||
|
||||
if start_date:
|
||||
query += ' AND order_date >= ?'
|
||||
params.append(start_date)
|
||||
|
||||
if end_date:
|
||||
query += ' AND order_date <= ?'
|
||||
params.append(end_date)
|
||||
|
||||
if status:
|
||||
query += ' AND status = ?'
|
||||
params.append(status)
|
||||
|
||||
query += ' ORDER BY created_at DESC LIMIT ?'
|
||||
params.append(limit)
|
||||
|
||||
cursor.execute(query, params)
|
||||
orders = [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
conn.close()
|
||||
return orders
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# AI 학습용 함수들
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def save_order_context(order_item_id: int, context: Dict) -> bool:
|
||||
"""
|
||||
주문 시점 컨텍스트 저장 (AI 학습용)
|
||||
|
||||
context: {
|
||||
'drug_code': '670400830',
|
||||
'product_name': '레바미피드정',
|
||||
'stock_at_order': 50,
|
||||
'usage_1d': 30,
|
||||
'usage_7d': 180,
|
||||
'usage_30d': 800,
|
||||
'ordered_spec': '30T',
|
||||
'ordered_qty': 10,
|
||||
'available_specs': ['30T', '300T'],
|
||||
'spec_stocks': {'30T': 50, '300T': 0},
|
||||
'selection_reason': 'stock_available'
|
||||
}
|
||||
"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
# 일평균 사용량 계산
|
||||
usage_30d = context.get('usage_30d', 0)
|
||||
avg_daily = usage_30d / 30.0 if usage_30d else 0
|
||||
|
||||
# 재고 소진 예상일 계산
|
||||
stock = context.get('stock_at_order', 0)
|
||||
days_until_stockout = stock / avg_daily if avg_daily > 0 else None
|
||||
|
||||
# 주문 총 정제수
|
||||
ordered_qty = context.get('ordered_qty', 0)
|
||||
spec = context.get('ordered_spec', '')
|
||||
unit_qty = int(''.join(filter(str.isdigit, spec))) if spec else 1
|
||||
ordered_dose = ordered_qty * unit_qty
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO order_context (
|
||||
order_item_id, drug_code, product_name,
|
||||
stock_at_order, usage_1d, usage_7d, usage_30d, avg_daily_usage,
|
||||
ordered_spec, ordered_qty, ordered_dose,
|
||||
available_specs, spec_stocks, selection_reason,
|
||||
days_until_stockout
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
order_item_id,
|
||||
context.get('drug_code'),
|
||||
context.get('product_name'),
|
||||
context.get('stock_at_order'),
|
||||
context.get('usage_1d'),
|
||||
context.get('usage_7d'),
|
||||
context.get('usage_30d'),
|
||||
avg_daily,
|
||||
context.get('ordered_spec'),
|
||||
ordered_qty,
|
||||
ordered_dose,
|
||||
json.dumps(context.get('available_specs', []), ensure_ascii=False),
|
||||
json.dumps(context.get('spec_stocks', {}), ensure_ascii=False),
|
||||
context.get('selection_reason'),
|
||||
days_until_stockout
|
||||
))
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_daily_usage(drug_code: str, usage_date: str,
|
||||
rx_count: int = 0, rx_qty: int = 0,
|
||||
pos_count: int = 0, pos_qty: int = 0,
|
||||
stock_end: int = None) -> bool:
|
||||
"""일별 사용량 업데이트 (UPSERT)"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
total_qty = rx_qty + pos_qty
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO daily_usage (
|
||||
drug_code, usage_date, rx_count, rx_qty, pos_count, pos_qty,
|
||||
total_qty, stock_end
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(drug_code, usage_date) DO UPDATE SET
|
||||
rx_count = rx_count + excluded.rx_count,
|
||||
rx_qty = rx_qty + excluded.rx_qty,
|
||||
pos_count = pos_count + excluded.pos_count,
|
||||
pos_qty = pos_qty + excluded.pos_qty,
|
||||
total_qty = total_qty + excluded.total_qty,
|
||||
stock_end = COALESCE(excluded.stock_end, stock_end)
|
||||
''', (drug_code, usage_date, rx_count, rx_qty, pos_count, pos_qty,
|
||||
total_qty, stock_end))
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_usage_stats(drug_code: str, days: int = 30) -> Dict:
|
||||
"""약품 사용량 통계 조회 (AI 분석용)"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
end_date = datetime.now().strftime('%Y-%m-%d')
|
||||
start_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cursor.execute('''
|
||||
SELECT
|
||||
COUNT(*) as days_with_data,
|
||||
SUM(total_qty) as total_usage,
|
||||
AVG(total_qty) as avg_daily,
|
||||
MAX(total_qty) as max_daily,
|
||||
MIN(total_qty) as min_daily
|
||||
FROM daily_usage
|
||||
WHERE drug_code = ? AND usage_date BETWEEN ? AND ?
|
||||
''', (drug_code, start_date, end_date))
|
||||
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
|
||||
if row and row['total_usage']:
|
||||
return {
|
||||
'drug_code': drug_code,
|
||||
'period_days': days,
|
||||
'days_with_data': row['days_with_data'],
|
||||
'total_usage': row['total_usage'],
|
||||
'avg_daily': round(row['avg_daily'], 2) if row['avg_daily'] else 0,
|
||||
'max_daily': row['max_daily'],
|
||||
'min_daily': row['min_daily']
|
||||
}
|
||||
|
||||
return {
|
||||
'drug_code': drug_code,
|
||||
'period_days': days,
|
||||
'days_with_data': 0,
|
||||
'total_usage': 0,
|
||||
'avg_daily': 0,
|
||||
'max_daily': 0,
|
||||
'min_daily': 0
|
||||
}
|
||||
|
||||
|
||||
def get_order_pattern(drug_code: str) -> Optional[Dict]:
|
||||
"""약품 주문 패턴 조회"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 최근 주문 이력 분석
|
||||
cursor.execute('''
|
||||
SELECT
|
||||
oi.specification,
|
||||
oi.order_qty,
|
||||
oi.total_dose,
|
||||
o.order_date
|
||||
FROM order_items oi
|
||||
JOIN orders o ON oi.order_id = o.id
|
||||
WHERE oi.drug_code = ? AND oi.status = 'success'
|
||||
ORDER BY o.order_date DESC
|
||||
LIMIT 10
|
||||
''', (drug_code,))
|
||||
|
||||
orders = [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
if not orders:
|
||||
conn.close()
|
||||
return None
|
||||
|
||||
# 가장 많이 사용된 규격
|
||||
spec_counts = {}
|
||||
for o in orders:
|
||||
spec = o['specification']
|
||||
spec_counts[spec] = spec_counts.get(spec, 0) + 1
|
||||
|
||||
typical_spec = max(spec_counts, key=spec_counts.get)
|
||||
|
||||
# 평균 주문 수량
|
||||
typical_qty = sum(o['order_qty'] for o in orders) // len(orders)
|
||||
|
||||
# 주문 주기 계산
|
||||
if len(orders) >= 2:
|
||||
dates = [datetime.strptime(o['order_date'], '%Y-%m-%d') for o in orders]
|
||||
intervals = [(dates[i] - dates[i+1]).days for i in range(len(dates)-1)]
|
||||
avg_interval = sum(intervals) / len(intervals) if intervals else 0
|
||||
else:
|
||||
avg_interval = 0
|
||||
|
||||
conn.close()
|
||||
|
||||
return {
|
||||
'drug_code': drug_code,
|
||||
'order_count': len(orders),
|
||||
'typical_spec': typical_spec,
|
||||
'typical_qty': typical_qty,
|
||||
'avg_order_interval_days': round(avg_interval, 1),
|
||||
'recent_orders': orders[:5]
|
||||
}
|
||||
|
||||
|
||||
def get_ai_training_data(limit: int = 1000) -> List[Dict]:
|
||||
"""AI 학습용 데이터 추출"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
SELECT
|
||||
oc.*,
|
||||
oi.status as order_status,
|
||||
oi.result_code,
|
||||
o.order_date,
|
||||
o.wholesaler_id
|
||||
FROM order_context oc
|
||||
JOIN order_items oi ON oc.order_item_id = oi.id
|
||||
JOIN orders o ON oi.order_id = o.id
|
||||
ORDER BY oc.created_at DESC
|
||||
LIMIT ?
|
||||
''', (limit,))
|
||||
|
||||
data = []
|
||||
for row in cursor.fetchall():
|
||||
item = dict(row)
|
||||
# JSON 필드 파싱
|
||||
if item.get('available_specs'):
|
||||
item['available_specs'] = json.loads(item['available_specs'])
|
||||
if item.get('spec_stocks'):
|
||||
item['spec_stocks'] = json.loads(item['spec_stocks'])
|
||||
data.append(item)
|
||||
|
||||
conn.close()
|
||||
return data
|
||||
|
||||
|
||||
def save_ai_pattern(drug_code: str, pattern: Dict) -> bool:
|
||||
"""AI 분석 결과 저장"""
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
today = datetime.now().strftime('%Y-%m-%d')
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO order_patterns (
|
||||
drug_code, analysis_date, analysis_period_days,
|
||||
avg_daily_usage, usage_stddev, peak_usage,
|
||||
typical_order_spec, typical_order_qty, order_frequency_days,
|
||||
recommended_spec, recommended_qty, recommended_reorder_point,
|
||||
confidence_score, model_version
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(drug_code, analysis_date) DO UPDATE SET
|
||||
avg_daily_usage = excluded.avg_daily_usage,
|
||||
recommended_spec = excluded.recommended_spec,
|
||||
recommended_qty = excluded.recommended_qty,
|
||||
confidence_score = excluded.confidence_score
|
||||
''', (
|
||||
drug_code,
|
||||
today,
|
||||
pattern.get('period_days', 30),
|
||||
pattern.get('avg_daily_usage'),
|
||||
pattern.get('usage_stddev'),
|
||||
pattern.get('peak_usage'),
|
||||
pattern.get('typical_order_spec'),
|
||||
pattern.get('typical_order_qty'),
|
||||
pattern.get('order_frequency_days'),
|
||||
pattern.get('recommended_spec'),
|
||||
pattern.get('recommended_qty'),
|
||||
pattern.get('recommended_reorder_point'),
|
||||
pattern.get('confidence_score'),
|
||||
pattern.get('model_version', 'v1')
|
||||
))
|
||||
|
||||
conn.commit()
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# 초기화 실행
|
||||
init_db()
|
||||
225
backend/paai_feedback.py
Normal file
@ -0,0 +1,225 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
PAAI 피드백 루프 시스템
|
||||
- 피드백 수집, AI 정제, 프롬프트 인젝션
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
paai_feedback_bp = Blueprint('paai_feedback', __name__)
|
||||
|
||||
# DB 경로
|
||||
DB_PATH = os.path.join(os.path.dirname(__file__), 'db', 'paai_feedback.db')
|
||||
|
||||
def get_db():
|
||||
"""DB 연결"""
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
def init_db():
|
||||
"""테이블 초기화"""
|
||||
conn = get_db()
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS paai_feedback (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- 컨텍스트
|
||||
prescription_id TEXT,
|
||||
patient_name TEXT,
|
||||
patient_context TEXT,
|
||||
|
||||
-- PAAI 응답
|
||||
paai_request TEXT,
|
||||
paai_response TEXT,
|
||||
|
||||
-- 피드백
|
||||
rating TEXT,
|
||||
category TEXT,
|
||||
pharmacist_comment TEXT,
|
||||
|
||||
-- AI 정제 결과
|
||||
refined_rule TEXT,
|
||||
confidence REAL,
|
||||
|
||||
-- 적용 상태
|
||||
applied_to_prompt INTEGER DEFAULT 0,
|
||||
applied_to_training INTEGER DEFAULT 0
|
||||
)
|
||||
''')
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# 앱 시작 시 테이블 생성
|
||||
init_db()
|
||||
|
||||
|
||||
@paai_feedback_bp.route('/api/paai/feedback', methods=['POST'])
|
||||
def submit_feedback():
|
||||
"""피드백 제출"""
|
||||
try:
|
||||
data = request.json
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO paai_feedback (
|
||||
prescription_id, patient_name, patient_context,
|
||||
paai_request, paai_response,
|
||||
rating, category, pharmacist_comment
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
data.get('prescription_id'),
|
||||
data.get('patient_name'),
|
||||
json.dumps(data.get('patient_context', {}), ensure_ascii=False),
|
||||
data.get('paai_request'),
|
||||
data.get('paai_response'),
|
||||
data.get('rating'), # 'good' or 'bad'
|
||||
data.get('category'), # 'interaction', 'indication', 'dosage', 'other'
|
||||
data.get('pharmacist_comment')
|
||||
))
|
||||
|
||||
feedback_id = cursor.lastrowid
|
||||
conn.commit()
|
||||
|
||||
# bad 피드백이고 코멘트가 있으면 AI 정제 시도
|
||||
if data.get('rating') == 'bad' and data.get('pharmacist_comment'):
|
||||
refined = refine_feedback_async(feedback_id, data)
|
||||
if refined:
|
||||
cursor.execute('''
|
||||
UPDATE paai_feedback
|
||||
SET refined_rule = ?, confidence = ?
|
||||
WHERE id = ?
|
||||
''', (refined['rule'], refined['confidence'], feedback_id))
|
||||
conn.commit()
|
||||
|
||||
conn.close()
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'feedback_id': feedback_id,
|
||||
'message': '피드백이 저장되었습니다.'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
def refine_feedback_async(feedback_id, data):
|
||||
"""피드백을 규칙으로 정제 (동기 버전 - 나중에 비동기로 변경 가능)"""
|
||||
try:
|
||||
# TODO: AI 호출로 정제
|
||||
# 지금은 간단히 코멘트를 규칙 형태로 저장
|
||||
comment = data.get('pharmacist_comment', '')
|
||||
if not comment:
|
||||
return None
|
||||
|
||||
# 간단한 규칙 형태로 변환
|
||||
category = data.get('category', 'other')
|
||||
rule = f"[{category}] {comment}"
|
||||
|
||||
return {
|
||||
'rule': rule,
|
||||
'confidence': 0.8 # 기본 신뢰도
|
||||
}
|
||||
except:
|
||||
return None
|
||||
|
||||
|
||||
@paai_feedback_bp.route('/api/paai/feedback/rules', methods=['GET'])
|
||||
def get_feedback_rules():
|
||||
"""축적된 피드백 규칙 조회 (프롬프트 인젝션용)"""
|
||||
try:
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# bad 피드백 중 정제된 규칙만
|
||||
cursor.execute('''
|
||||
SELECT refined_rule, category, created_at
|
||||
FROM paai_feedback
|
||||
WHERE rating = 'bad'
|
||||
AND refined_rule IS NOT NULL
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 20
|
||||
''')
|
||||
|
||||
rules = []
|
||||
for row in cursor.fetchall():
|
||||
rules.append({
|
||||
'rule': row['refined_rule'],
|
||||
'category': row['category'],
|
||||
'created_at': row['created_at']
|
||||
})
|
||||
|
||||
conn.close()
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'rules': rules,
|
||||
'count': len(rules)
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@paai_feedback_bp.route('/api/paai/feedback/stats', methods=['GET'])
|
||||
def get_feedback_stats():
|
||||
"""피드백 통계"""
|
||||
try:
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
SUM(CASE WHEN rating = 'good' THEN 1 ELSE 0 END) as good,
|
||||
SUM(CASE WHEN rating = 'bad' THEN 1 ELSE 0 END) as bad
|
||||
FROM paai_feedback
|
||||
''')
|
||||
row = cursor.fetchone()
|
||||
|
||||
conn.close()
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'stats': {
|
||||
'total': row['total'] or 0,
|
||||
'good': row['good'] or 0,
|
||||
'bad': row['bad'] or 0
|
||||
}
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
def get_rules_for_prompt(patient_context=None):
|
||||
"""프롬프트에 주입할 규칙 목록 반환"""
|
||||
try:
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 최근 규칙 20개
|
||||
cursor.execute('''
|
||||
SELECT refined_rule
|
||||
FROM paai_feedback
|
||||
WHERE rating = 'bad'
|
||||
AND refined_rule IS NOT NULL
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 20
|
||||
''')
|
||||
|
||||
rules = [row['refined_rule'] for row in cursor.fetchall()]
|
||||
conn.close()
|
||||
|
||||
return rules
|
||||
except:
|
||||
return []
|
||||
159
backend/paai_printer.py
Normal file
@ -0,0 +1,159 @@
|
||||
"""PAAI ESC/POS 프린터 모듈"""
|
||||
import json
|
||||
from datetime import datetime
|
||||
from escpos.printer import Network
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
# 프린터 설정
|
||||
PRINTER_IP = "192.168.0.174"
|
||||
PRINTER_PORT = 9100
|
||||
THERMAL_WIDTH = 576
|
||||
|
||||
|
||||
def print_paai_result(pre_serial: str, patient_name: str, analysis: dict, kims_summary: dict) -> dict:
|
||||
"""PAAI 분석 결과 인쇄"""
|
||||
try:
|
||||
# 이미지 생성
|
||||
img = create_receipt_image(pre_serial, patient_name, analysis, kims_summary)
|
||||
|
||||
# 프린터 연결 및 출력
|
||||
p = Network(PRINTER_IP, port=PRINTER_PORT, timeout=15)
|
||||
p.image(img)
|
||||
p.text('\n\n\n')
|
||||
p.cut()
|
||||
|
||||
return {'success': True, 'message': '인쇄 완료'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
|
||||
def create_receipt_image(pre_serial: str, patient_name: str, analysis: dict, kims_summary: dict) -> Image:
|
||||
"""영수증 이미지 생성"""
|
||||
# 폰트
|
||||
try:
|
||||
font_title = ImageFont.truetype('malgun.ttf', 28)
|
||||
font_section = ImageFont.truetype('malgunbd.ttf', 20)
|
||||
font_normal = ImageFont.truetype('malgun.ttf', 18)
|
||||
font_small = ImageFont.truetype('malgun.ttf', 15)
|
||||
except:
|
||||
font_title = ImageFont.load_default()
|
||||
font_section = font_title
|
||||
font_normal = font_title
|
||||
font_small = font_title
|
||||
|
||||
width = THERMAL_WIDTH
|
||||
padding = 20
|
||||
y = padding
|
||||
|
||||
# 이미지 생성
|
||||
img = Image.new('RGB', (width, 1000), 'white')
|
||||
draw = ImageDraw.Draw(img)
|
||||
|
||||
# 헤더
|
||||
draw.text((width//2, y), 'PAAI 복약안내', font=font_title, fill='black', anchor='mt')
|
||||
y += 40
|
||||
draw.line([(padding, y), (width-padding, y)], fill='black', width=1)
|
||||
y += 15
|
||||
|
||||
# 환자 정보
|
||||
draw.text((padding, y), f'환자: {patient_name}', font=font_normal, fill='black')
|
||||
y += 25
|
||||
draw.text((padding, y), f'처방번호: {pre_serial}', font=font_small, fill='black')
|
||||
y += 20
|
||||
now_str = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
draw.text((padding, y), f'출력: {now_str}', font=font_small, fill='black')
|
||||
y += 25
|
||||
draw.line([(padding, y), (width-padding, y)], fill='black', width=1)
|
||||
y += 15
|
||||
|
||||
# 상호작용
|
||||
interaction_count = kims_summary.get('interaction_count', 0)
|
||||
has_severe = kims_summary.get('has_severe', False)
|
||||
|
||||
if has_severe:
|
||||
draw.text((padding, y), '[주의] 중증 상호작용 있음!', font=font_section, fill='black')
|
||||
elif interaction_count > 0:
|
||||
draw.text((padding, y), f'약물 상호작용: {interaction_count}건', font=font_normal, fill='black')
|
||||
else:
|
||||
draw.text((padding, y), '상호작용 없음', font=font_normal, fill='black')
|
||||
y += 30
|
||||
|
||||
# 처방 해석
|
||||
insight = analysis.get('prescription_insight', '')
|
||||
if insight:
|
||||
draw.text((padding, y), '[처방 해석]', font=font_section, fill='black')
|
||||
y += 28
|
||||
for line in wrap_text(insight, 40)[:3]:
|
||||
draw.text((padding, y), line, font=font_small, fill='black')
|
||||
y += 20
|
||||
y += 10
|
||||
|
||||
# 주의사항
|
||||
cautions = analysis.get('cautions', [])
|
||||
if cautions:
|
||||
draw.text((padding, y), '[복용 주의사항]', font=font_section, fill='black')
|
||||
y += 28
|
||||
for i, c in enumerate(cautions[:3], 1):
|
||||
for line in wrap_text(f'{i}. {c}', 40)[:2]:
|
||||
draw.text((padding, y), line, font=font_small, fill='black')
|
||||
y += 20
|
||||
y += 10
|
||||
|
||||
# 상담 포인트
|
||||
counseling = analysis.get('counseling_points', [])
|
||||
if counseling:
|
||||
draw.text((padding, y), '[상담 포인트]', font=font_section, fill='black')
|
||||
y += 28
|
||||
for i, c in enumerate(counseling[:2], 1):
|
||||
for line in wrap_text(f'{i}. {c}', 40)[:2]:
|
||||
draw.text((padding, y), line, font=font_small, fill='black')
|
||||
y += 20
|
||||
y += 10
|
||||
|
||||
# 푸터
|
||||
y += 10
|
||||
draw.line([(padding, y), (width-padding, y)], fill='black', width=1)
|
||||
y += 15
|
||||
draw.text((width//2, y), '양구청춘약국 PAAI', font=font_small, fill='black', anchor='mt')
|
||||
|
||||
return img.crop((0, 0, width, y + 30))
|
||||
|
||||
|
||||
def wrap_text(text: str, max_chars: int = 40) -> list:
|
||||
"""텍스트 줄바꿈"""
|
||||
lines = []
|
||||
words = text.split()
|
||||
current = ""
|
||||
|
||||
for word in words:
|
||||
if len(current) + len(word) + 1 <= max_chars:
|
||||
current = current + " " + word if current else word
|
||||
else:
|
||||
if current:
|
||||
lines.append(current)
|
||||
current = word
|
||||
|
||||
if current:
|
||||
lines.append(current)
|
||||
|
||||
return lines if lines else [text[:max_chars]]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# CLI 테스트
|
||||
import sys
|
||||
if len(sys.argv) > 1:
|
||||
pre_serial = sys.argv[1]
|
||||
else:
|
||||
pre_serial = '20260305000075'
|
||||
|
||||
# 테스트 데이터
|
||||
analysis = {
|
||||
'prescription_insight': '테스트 처방입니다.',
|
||||
'cautions': ['주의사항 1', '주의사항 2'],
|
||||
'counseling_points': ['상담 포인트 1']
|
||||
}
|
||||
kims_summary = {'interaction_count': 0, 'has_severe': False}
|
||||
|
||||
result = print_paai_result(pre_serial, '테스트환자', analysis, kims_summary)
|
||||
print(result)
|
||||
201
backend/paai_printer_cli.py
Normal file
@ -0,0 +1,201 @@
|
||||
"""PAAI ESC/POS 프린터 CLI - EUC-KR 텍스트 방식"""
|
||||
import sys
|
||||
import json
|
||||
import socket
|
||||
from datetime import datetime
|
||||
|
||||
# 프린터 설정
|
||||
PRINTER_IP = "192.168.0.174"
|
||||
PRINTER_PORT = 9100
|
||||
|
||||
# ESC/POS 명령어
|
||||
ESC = b'\x1b'
|
||||
INIT = ESC + b'@' # 프린터 초기화
|
||||
CUT = ESC + b'd\x03' # 피드 + 커트
|
||||
|
||||
|
||||
def print_raw(data: bytes) -> bool:
|
||||
"""바이트 데이터를 프린터로 전송"""
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(10)
|
||||
sock.connect((PRINTER_IP, PRINTER_PORT))
|
||||
sock.sendall(data)
|
||||
sock.close()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"프린터 오류: {e}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def wrap_text(text: str, width: int = 44) -> list:
|
||||
"""텍스트 줄바꿈 (44자 기준, 들여쓰기 고려)"""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
lines = []
|
||||
words = text.split()
|
||||
current = ""
|
||||
|
||||
for word in words:
|
||||
if len(current) + len(word) + 1 <= width:
|
||||
current = current + " " + word if current else word
|
||||
else:
|
||||
if current:
|
||||
lines.append(current)
|
||||
current = word
|
||||
|
||||
if current:
|
||||
lines.append(current)
|
||||
|
||||
return lines if lines else [text[:width]]
|
||||
|
||||
|
||||
def center_text(text: str, width: int = 48) -> str:
|
||||
"""중앙 정렬"""
|
||||
text_len = len(text)
|
||||
if text_len >= width:
|
||||
return text
|
||||
spaces = (width - text_len) // 2
|
||||
return " " * spaces + text
|
||||
|
||||
|
||||
def format_paai_receipt(pre_serial: str, patient_name: str,
|
||||
analysis: dict, kims_summary: dict) -> str:
|
||||
"""PAAI 복약안내 영수증 텍스트 생성 (48자 기준)"""
|
||||
|
||||
LINE = "=" * 48
|
||||
THIN = "-" * 48
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
# 헤더
|
||||
msg = f"\n{LINE}\n"
|
||||
msg += center_text("[ PAAI 복약안내 ]") + "\n"
|
||||
msg += f"{LINE}\n"
|
||||
|
||||
# 환자 정보
|
||||
msg += f"환자: {patient_name}\n"
|
||||
msg += f"처방번호: {pre_serial}\n"
|
||||
msg += f"출력: {now}\n"
|
||||
msg += f"{THIN}\n"
|
||||
|
||||
# 상호작용 요약
|
||||
interaction_count = kims_summary.get('interaction_count', 0)
|
||||
has_severe = kims_summary.get('has_severe', False)
|
||||
|
||||
if has_severe:
|
||||
msg += "[!!] 중증 상호작용 있음!\n"
|
||||
elif interaction_count > 0:
|
||||
msg += f"[!] 약물 상호작용: {interaction_count}건\n"
|
||||
else:
|
||||
msg += "[V] 상호작용 없음\n"
|
||||
msg += "\n"
|
||||
|
||||
# 처방 해석
|
||||
insight = analysis.get('prescription_insight', '')
|
||||
if insight:
|
||||
msg += f"{THIN}\n"
|
||||
msg += ">> 처방 해석\n"
|
||||
for line in wrap_text(insight, 44):
|
||||
msg += f" {line}\n"
|
||||
msg += "\n"
|
||||
|
||||
# 복용 주의사항
|
||||
cautions = analysis.get('cautions', [])
|
||||
if cautions:
|
||||
msg += f"{THIN}\n"
|
||||
msg += ">> 복용 주의사항\n"
|
||||
for i, caution in enumerate(cautions[:4], 1):
|
||||
# 첫 줄
|
||||
first_line = True
|
||||
for line in wrap_text(f"{i}. {caution}", 44):
|
||||
if first_line:
|
||||
msg += f" {line}\n"
|
||||
first_line = False
|
||||
else:
|
||||
msg += f" {line}\n"
|
||||
msg += "\n"
|
||||
|
||||
# 상담 포인트
|
||||
counseling = analysis.get('counseling_points', [])
|
||||
if counseling:
|
||||
msg += f"{THIN}\n"
|
||||
msg += ">> 상담 포인트\n"
|
||||
for i, point in enumerate(counseling[:3], 1):
|
||||
first_line = True
|
||||
for line in wrap_text(f"{i}. {point}", 44):
|
||||
if first_line:
|
||||
msg += f" {line}\n"
|
||||
first_line = False
|
||||
else:
|
||||
msg += f" {line}\n"
|
||||
msg += "\n"
|
||||
|
||||
# OTC 추천
|
||||
otc_recs = analysis.get('otc_recommendations', [])
|
||||
if otc_recs:
|
||||
msg += f"{THIN}\n"
|
||||
msg += ">> OTC 추천\n"
|
||||
for rec in otc_recs[:2]:
|
||||
product = rec.get('product', '')
|
||||
reason = rec.get('reason', '')
|
||||
msg += f" - {product}\n"
|
||||
for line in wrap_text(reason, 42):
|
||||
msg += f" {line}\n"
|
||||
msg += "\n"
|
||||
|
||||
# 푸터
|
||||
msg += f"{LINE}\n"
|
||||
msg += center_text("양구청춘약국 PAAI") + "\n"
|
||||
msg += center_text("Tel: 033-481-5222") + "\n"
|
||||
msg += "\n"
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
def print_paai_receipt(data: dict) -> bool:
|
||||
"""PAAI 영수증 인쇄"""
|
||||
try:
|
||||
pre_serial = data.get('pre_serial', '')
|
||||
patient_name = data.get('patient_name', '')
|
||||
analysis = data.get('analysis', {})
|
||||
kims_summary = data.get('kims_summary', {})
|
||||
|
||||
# 텍스트 생성
|
||||
message = format_paai_receipt(pre_serial, patient_name, analysis, kims_summary)
|
||||
|
||||
# EUC-KR 인코딩 (한글 지원)
|
||||
text_bytes = message.encode('euc-kr', errors='replace')
|
||||
|
||||
# 명령어 조합
|
||||
command = INIT + text_bytes + b'\n\n\n' + CUT
|
||||
|
||||
return print_raw(command)
|
||||
except Exception as e:
|
||||
print(f"인쇄 오류: {e}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("사용법: python paai_printer_cli.py <json_file>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
json_path = sys.argv[1]
|
||||
|
||||
try:
|
||||
with open(json_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
if print_paai_receipt(data):
|
||||
print("인쇄 완료")
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"오류: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
2167
backend/pmr_api.py
Normal file
169
backend/pos_printer.py
Normal file
@ -0,0 +1,169 @@
|
||||
# pos_printer.py - ESC/POS 영수증 프린터 유틸리티
|
||||
# 0bin-label-app/src/pos_settings_dialog.py 기반
|
||||
|
||||
import socket
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
# 프린터 설정 (config에서 불러올 수도 있음)
|
||||
POS_PRINTER_IP = "192.168.0.174"
|
||||
POS_PRINTER_PORT = 9100
|
||||
POS_PRINTER_NAME = "올댓포스 오른쪽"
|
||||
|
||||
# ESC/POS 명령어
|
||||
ESC = b'\x1b'
|
||||
GS = b'\x1d'
|
||||
|
||||
# 기본 명령
|
||||
INIT = ESC + b'@' # 프린터 초기화
|
||||
CUT = ESC + b'd\x03' # 피드 + 커트 (원본 방식)
|
||||
FEED = b'\n\n\n' # 줄바꿈
|
||||
|
||||
# 정렬
|
||||
ALIGN_LEFT = ESC + b'a\x00'
|
||||
ALIGN_CENTER = ESC + b'a\x01'
|
||||
ALIGN_RIGHT = ESC + b'a\x02'
|
||||
|
||||
# 폰트 스타일
|
||||
BOLD_ON = ESC + b'E\x01'
|
||||
BOLD_OFF = ESC + b'E\x00'
|
||||
DOUBLE_HEIGHT = ESC + b'!\x10'
|
||||
DOUBLE_WIDTH = ESC + b'!\x20'
|
||||
DOUBLE_SIZE = ESC + b'!\x30' # 가로세로 2배
|
||||
NORMAL_SIZE = ESC + b'!\x00'
|
||||
|
||||
# 로깅
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def print_raw(data: bytes, ip: str = None, port: int = None) -> bool:
|
||||
"""
|
||||
ESC/POS 바이트 데이터를 프린터로 전송
|
||||
|
||||
Args:
|
||||
data: ESC/POS 명령어 + 텍스트 바이트
|
||||
ip: 프린터 IP (기본값: POS_PRINTER_IP)
|
||||
port: 프린터 포트 (기본값: POS_PRINTER_PORT)
|
||||
|
||||
Returns:
|
||||
bool: 성공 여부
|
||||
"""
|
||||
ip = ip or POS_PRINTER_IP
|
||||
port = port or POS_PRINTER_PORT
|
||||
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(5)
|
||||
sock.connect((ip, port))
|
||||
sock.sendall(data)
|
||||
sock.close()
|
||||
logging.info(f"[POS Printer] 전송 성공: {ip}:{port}")
|
||||
return True
|
||||
except socket.timeout:
|
||||
logging.error(f"[POS Printer] 연결 시간 초과: {ip}:{port}")
|
||||
return False
|
||||
except ConnectionRefusedError:
|
||||
logging.error(f"[POS Printer] 연결 거부됨: {ip}:{port}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logging.error(f"[POS Printer] 전송 실패: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def print_text(text: str, cut: bool = True) -> bool:
|
||||
"""
|
||||
텍스트를 영수증 프린터로 출력
|
||||
|
||||
Args:
|
||||
text: 출력할 텍스트 (한글 지원)
|
||||
cut: 출력 후 용지 커트 여부
|
||||
|
||||
Returns:
|
||||
bool: 성공 여부
|
||||
"""
|
||||
try:
|
||||
# EUC-KR 인코딩 (한글 지원)
|
||||
text_bytes = text.encode('euc-kr', errors='replace')
|
||||
|
||||
# 명령어 조합
|
||||
command = INIT + text_bytes + b'\n\n\n'
|
||||
if cut:
|
||||
command += CUT
|
||||
|
||||
return print_raw(command)
|
||||
except Exception as e:
|
||||
logging.error(f"[POS Printer] 텍스트 인쇄 실패: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def print_cusetc(customer_name: str, cusetc: str, phone: str = None) -> bool:
|
||||
"""
|
||||
특이(참고)사항 영수증 출력 (단순 텍스트 방식)
|
||||
|
||||
Args:
|
||||
customer_name: 고객 이름
|
||||
cusetc: 특이사항 내용
|
||||
phone: 전화번호 (선택)
|
||||
|
||||
Returns:
|
||||
bool: 성공 여부
|
||||
"""
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M')
|
||||
|
||||
# 전화번호 포맷팅
|
||||
phone_display = ""
|
||||
if phone:
|
||||
phone_clean = phone.replace("-", "").replace(" ", "")
|
||||
if len(phone_clean) == 11:
|
||||
phone_display = f"{phone_clean[:3]}-{phone_clean[3:7]}-{phone_clean[7:]}"
|
||||
else:
|
||||
phone_display = phone
|
||||
|
||||
# 80mm 프린터 = 48자 기준
|
||||
LINE = "=" * 48
|
||||
THIN = "-" * 48
|
||||
|
||||
message = f"""
|
||||
{LINE}
|
||||
[ 특이사항 ]
|
||||
{LINE}
|
||||
고객: {customer_name}
|
||||
"""
|
||||
if phone_display:
|
||||
message += f"연락처: {phone_display}\n"
|
||||
|
||||
message += f"""출력: {now}
|
||||
{THIN}
|
||||
{cusetc}
|
||||
{LINE}
|
||||
청춘약국
|
||||
"""
|
||||
|
||||
return print_text(message, cut=True)
|
||||
|
||||
|
||||
def test_print() -> bool:
|
||||
"""테스트 인쇄"""
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
test_message = f"""
|
||||
================================
|
||||
POS 프린터 테스트
|
||||
================================
|
||||
|
||||
IP: {POS_PRINTER_IP}
|
||||
Port: {POS_PRINTER_PORT}
|
||||
Time: {now}
|
||||
|
||||
청춘약국 마일리지 시스템
|
||||
ESC/POS 정상 작동!
|
||||
================================
|
||||
"""
|
||||
return print_text(test_message, cut=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 테스트
|
||||
print("POS 프린터 테스트 인쇄...")
|
||||
result = test_print()
|
||||
print(f"결과: {'성공' if result else '실패'}")
|
||||
305
backend/scripts/batch_apc_matching.py
Normal file
@ -0,0 +1,305 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
동물약 일괄 APC 매칭 (개선판)
|
||||
- 띄어쓰기 무시 매칭
|
||||
- 체중 범위로 정밀 매칭
|
||||
- dry-run 모드 (검증용)
|
||||
"""
|
||||
import sys, io, re
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text, create_engine
|
||||
from datetime import datetime
|
||||
|
||||
DRY_RUN = True # True: 검증만, False: 실제 INSERT
|
||||
|
||||
# ── 유틸 함수 ──
|
||||
|
||||
def normalize(name):
|
||||
"""띄어쓰기/특수문자 제거하여 비교용 문자열 생성"""
|
||||
# 공백, 하이픈, 점 제거
|
||||
return re.sub(r'[\s\-\.]+', '', name).lower()
|
||||
|
||||
def extract_base_name(mssql_name):
|
||||
"""MSSQL 제품명에서 검색용 기본명 추출 (여러 후보 반환)
|
||||
예: '다이로하트정M(12~22kg)' → ['다이로하트정', '다이로하트']
|
||||
'하트캅츄어블(11kg이하)' → ['하트캅츄어블', '하트캅']
|
||||
'클라펫정50(100정)' → ['클라펫정50', '클라펫정', '클라펫']
|
||||
"""
|
||||
name = mssql_name.replace('(판)', '')
|
||||
# 사이즈 라벨(XS/SS/S/M/L/XL/mini) + 괄호 이전까지
|
||||
m = re.match(r'^(.+?)(XS|SS|XL|xs|mini|S|M|L)?\s*[\(/]', name)
|
||||
if m:
|
||||
base = m.group(1)
|
||||
else:
|
||||
base = re.sub(r'[\(/].*', '', name)
|
||||
base = base.strip()
|
||||
|
||||
candidates = [base]
|
||||
# 끝의 숫자 제거: 클라펫정50 → 클라펫정
|
||||
no_num = re.sub(r'\d+$', '', base)
|
||||
if no_num and no_num != base:
|
||||
candidates.append(no_num)
|
||||
# 제형 접미사 제거: 다이로하트정 → 다이로하트, 하트캅츄어블 → 하트캅
|
||||
for suffix in ['츄어블', '정', '액', '캡슐', '산', '시럽']:
|
||||
for c in list(candidates):
|
||||
stripped = re.sub(suffix + r'$', '', c)
|
||||
if stripped and stripped != c and stripped not in candidates:
|
||||
candidates.append(stripped)
|
||||
return candidates
|
||||
|
||||
def extract_weight_range(mssql_name):
|
||||
"""MSSQL 제품명에서 체중 범위 추출
|
||||
'가드닐L(20~40kg)' → (20, 40)
|
||||
'셀라이트액SS(2.5kg이하)' → (0, 2.5)
|
||||
'파라캅L(5kg이상)' → (5, 999)
|
||||
'하트웜솔루션츄어블S(11kg이하)' → (0, 11)
|
||||
'다이로하트정S(5.6~11kg)' → (5.6, 11)
|
||||
"""
|
||||
# 범위: (5.6~11kg), (2~10kg)
|
||||
m = re.search(r'\((\d+\.?\d*)[-~](\d+\.?\d*)\s*kg\)', mssql_name)
|
||||
if m:
|
||||
return float(m.group(1)), float(m.group(2))
|
||||
|
||||
# 이하: (2.5kg이하), (11kg이하)
|
||||
m = re.search(r'\((\d+\.?\d*)\s*kg\s*이하\)', mssql_name)
|
||||
if m:
|
||||
return 0, float(m.group(1))
|
||||
|
||||
# 이상: (5kg이상)
|
||||
m = re.search(r'\((\d+\.?\d*)\s*kg\s*이상\)', mssql_name)
|
||||
if m:
|
||||
return float(m.group(1)), 999
|
||||
|
||||
return None, None
|
||||
|
||||
def weight_match(mssql_min, mssql_max, pg_min, pg_max):
|
||||
"""체중 범위가 일치하는지 확인 (약간의 오차 허용)"""
|
||||
if pg_min is None or pg_max is None:
|
||||
return False
|
||||
# 이상(999)인 경우 pg_max도 큰 값이면 OK
|
||||
if mssql_max == 999 and pg_max >= 50:
|
||||
return abs(mssql_min - pg_min) <= 1
|
||||
return abs(mssql_min - pg_min) <= 1 and abs(mssql_max - pg_max) <= 1
|
||||
|
||||
|
||||
# ── 1. MSSQL 동물약 (APC 없는 것만) ──
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
result = session.execute(text("""
|
||||
SELECT
|
||||
G.DrugCode,
|
||||
G.GoodsName,
|
||||
G.Saleprice,
|
||||
(
|
||||
SELECT TOP 1 U.CD_CD_BARCODE
|
||||
FROM CD_ITEM_UNIT_MEMBER U
|
||||
WHERE U.DRUGCODE = G.DrugCode
|
||||
AND U.CD_CD_BARCODE LIKE '023%'
|
||||
) AS APC_CODE
|
||||
FROM CD_GOODS G
|
||||
WHERE G.POS_BOON = '010103'
|
||||
AND G.GoodsSelCode = 'B'
|
||||
ORDER BY G.GoodsName
|
||||
"""))
|
||||
|
||||
no_apc = []
|
||||
for row in result:
|
||||
if not row.APC_CODE:
|
||||
no_apc.append({
|
||||
'code': row.DrugCode,
|
||||
'name': row.GoodsName,
|
||||
'price': row.Saleprice
|
||||
})
|
||||
|
||||
session.close()
|
||||
|
||||
print(f'=== APC 없는 동물약: {len(no_apc)}개 ===')
|
||||
print(f'=== 모드: {"DRY-RUN (검증만)" if DRY_RUN else "실제 INSERT"} ===\n')
|
||||
|
||||
# ── 2. PostgreSQL에서 매칭 ──
|
||||
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
|
||||
|
||||
matched = [] # 확정 매칭
|
||||
ambiguous = [] # 후보 여러 개 (수동 확인 필요)
|
||||
no_match = [] # 매칭 없음
|
||||
|
||||
for drug in no_apc:
|
||||
name = drug['name']
|
||||
base_names = extract_base_name(name)
|
||||
w_min, w_max = extract_weight_range(name)
|
||||
|
||||
# 여러 기본명 후보로 검색 (좁은 것부터 시도)
|
||||
candidates = []
|
||||
used_base = None
|
||||
for bn in base_names:
|
||||
norm_base = normalize(bn)
|
||||
result = pg.execute(text("""
|
||||
SELECT apc, product_name,
|
||||
weight_min_kg, weight_max_kg,
|
||||
dosage,
|
||||
llm_pharm->>'사용가능 동물' as target
|
||||
FROM apc
|
||||
WHERE REGEXP_REPLACE(LOWER(product_name), '[\\s\\-\\.]+', '', 'g') LIKE :pattern
|
||||
ORDER BY product_name
|
||||
"""), {'pattern': f'%{norm_base}%'})
|
||||
candidates = list(result)
|
||||
if candidates:
|
||||
used_base = bn
|
||||
break
|
||||
if not used_base:
|
||||
used_base = base_names[0]
|
||||
|
||||
if not candidates:
|
||||
no_match.append(drug)
|
||||
print(f'❌ {name}')
|
||||
print(f' 기본명: {base_names} → 매칭 없음')
|
||||
continue
|
||||
|
||||
# ── 단계별 필터링 ──
|
||||
|
||||
# (A) 제형 필터: MSSQL 이름에 "정"이 있으면 PG에서도 "정" 포함 우선
|
||||
filtered = candidates
|
||||
for form in ['정', '액', '캡슐']:
|
||||
if form in name.split('(')[0]:
|
||||
form_match = [c for c in filtered if form in c.product_name]
|
||||
if form_match:
|
||||
filtered = form_match
|
||||
break
|
||||
|
||||
# (B) 체중 범위로 정밀 매칭
|
||||
if w_min is not None:
|
||||
exact = [c for c in filtered
|
||||
if weight_match(w_min, w_max, c.weight_min_kg, c.weight_max_kg)]
|
||||
if exact:
|
||||
filtered = exact
|
||||
|
||||
# (C) 포장단위 여러 개면 최소 포장 선택 (낱개 판매 기준)
|
||||
# "/ 6 정", "/ 1 피펫" 등에서 숫자 추출
|
||||
if len(filtered) > 1:
|
||||
def extract_pack_qty(pname):
|
||||
m = re.search(r'/\s*(\d+)\s*(정|피펫|개|포)', pname)
|
||||
return int(m.group(1)) if m else 0
|
||||
has_qty = [(c, extract_pack_qty(c.product_name)) for c in filtered]
|
||||
# 포장수량이 있는 것들만 필터
|
||||
with_qty = [(c, q) for c, q in has_qty if q > 0]
|
||||
if with_qty:
|
||||
min_qty = min(q for _, q in with_qty)
|
||||
filtered = [c for c, q in with_qty if q == min_qty]
|
||||
|
||||
# (D) 그래도 여러 개면 대표 APC (product_name이 가장 짧은 것) 선택
|
||||
if len(filtered) > 1:
|
||||
# 포장수량 정보가 없는 대표 코드가 있으면 우선
|
||||
no_qty = [c for c in filtered if '/' not in c.product_name]
|
||||
if len(no_qty) == 1:
|
||||
filtered = no_qty
|
||||
|
||||
# ── 결과 판정 ──
|
||||
if len(filtered) == 1:
|
||||
method = '체중매칭' if w_min is not None and filtered[0].weight_min_kg is not None else '유일후보'
|
||||
matched.append({
|
||||
'mssql': drug,
|
||||
'apc': filtered[0],
|
||||
'method': method
|
||||
})
|
||||
print(f'✅ {name}')
|
||||
print(f' → {filtered[0].apc}: {filtered[0].product_name}')
|
||||
if w_min is not None and filtered[0].weight_min_kg is not None:
|
||||
print(f' 체중: MSSQL({w_min}~{w_max}kg) = PG({filtered[0].weight_min_kg}~{filtered[0].weight_max_kg}kg)')
|
||||
continue
|
||||
|
||||
# 후보가 0개 (필터가 너무 강했으면 원래 candidates로 복구)
|
||||
if len(filtered) == 0:
|
||||
filtered = candidates
|
||||
|
||||
# 수동 확인
|
||||
ambiguous.append({
|
||||
'mssql': drug,
|
||||
'candidates': filtered,
|
||||
'reason': f'후보 {len(filtered)}건'
|
||||
})
|
||||
print(f'⚠️ {name} - 후보 {len(filtered)}건 (수동 확인)')
|
||||
for c in filtered[:5]:
|
||||
wt = f'({c.weight_min_kg}~{c.weight_max_kg}kg)' if c.weight_min_kg else ''
|
||||
print(f' → {c.apc}: {c.product_name} {wt}')
|
||||
|
||||
pg.close()
|
||||
|
||||
# ── 3. 요약 ──
|
||||
|
||||
print(f'\n{"="*50}')
|
||||
print(f'=== 매칭 요약 ===')
|
||||
print(f'APC 없는 제품: {len(no_apc)}개')
|
||||
print(f'✅ 확정 매칭: {len(matched)}개')
|
||||
print(f'⚠️ 수동 확인: {len(ambiguous)}개')
|
||||
print(f'❌ 매칭 없음: {len(no_match)}개')
|
||||
|
||||
if matched:
|
||||
print(f'\n{"="*50}')
|
||||
print(f'=== 확정 매칭 목록 (INSERT 대상) ===')
|
||||
for m in matched:
|
||||
d = m['mssql']
|
||||
a = m['apc']
|
||||
print(f' {d["name"]:40s} → {a.apc} [{m["method"]}]')
|
||||
|
||||
# ── 4. INSERT (DRY_RUN=False일 때만) ──
|
||||
|
||||
if matched and not DRY_RUN:
|
||||
print(f'\n{"="*50}')
|
||||
print(f'=== INSERT 실행 ===')
|
||||
session = get_db_session('PM_DRUG')
|
||||
today = datetime.now().strftime('%Y%m%d')
|
||||
|
||||
for m in matched:
|
||||
drugcode = m['mssql']['code']
|
||||
apc = m['apc'].apc
|
||||
|
||||
# 기존 가격 조회
|
||||
existing = session.execute(text("""
|
||||
SELECT TOP 1 CD_MY_UNIT, CD_IN_UNIT
|
||||
FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = :dc
|
||||
ORDER BY SN DESC
|
||||
"""), {'dc': drugcode}).fetchone()
|
||||
|
||||
if not existing:
|
||||
print(f' ❌ {m["mssql"]["name"]}: 기존 레코드 없음')
|
||||
continue
|
||||
|
||||
# 중복 확인
|
||||
check = session.execute(text("""
|
||||
SELECT 1 FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = :dc AND CD_CD_BARCODE = :apc
|
||||
"""), {'dc': drugcode, 'apc': apc}).fetchone()
|
||||
|
||||
if check:
|
||||
print(f' ⏭️ {m["mssql"]["name"]}: 이미 등록됨')
|
||||
continue
|
||||
|
||||
try:
|
||||
session.execute(text("""
|
||||
INSERT INTO CD_ITEM_UNIT_MEMBER (
|
||||
DRUGCODE, CD_CD_UNIT, CD_NM_UNIT, CD_MY_UNIT, CD_IN_UNIT,
|
||||
CD_CD_BARCODE, CD_CD_POS, CHANGE_DATE
|
||||
) VALUES (
|
||||
:drugcode, '015', 1.0, :my_unit, :in_unit,
|
||||
:barcode, '', :change_date
|
||||
)
|
||||
"""), {
|
||||
'drugcode': drugcode,
|
||||
'my_unit': existing.CD_MY_UNIT,
|
||||
'in_unit': existing.CD_IN_UNIT,
|
||||
'barcode': apc,
|
||||
'change_date': today
|
||||
})
|
||||
session.commit()
|
||||
print(f' ✅ {m["mssql"]["name"]} → {apc}')
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f' ❌ {m["mssql"]["name"]}: {e}')
|
||||
|
||||
session.close()
|
||||
print('\n완료!')
|
||||
84
backend/scripts/batch_insert_apc.py
Normal file
@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
확실한 매칭만 일괄 등록
|
||||
"""
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
from datetime import datetime
|
||||
|
||||
# 확실한 매칭 목록 (MSSQL 제품명, DrugCode, APC)
|
||||
MAPPINGS = [
|
||||
# 파라캅
|
||||
('파라캅L(5kg이상)', 'LB000003159', '0230338510101'), # 파라캅 L 정 10정
|
||||
('파라캅S(5kg이하)', 'LB000003160', '0230347110106'), # 파라캅 에스 정 10정
|
||||
# 세레니아
|
||||
('세레니아정16mg(개멀미약)', 'LB000003353', '0231884610109'), # 세레니아 정 16mg / 4정
|
||||
('세레니아정24mg(개멀미약)', 'LB000003354', '0231884620107'), # 세레니아 정 24mg / 4정
|
||||
# ── 2차 매칭 (2026-03-08) ──
|
||||
# 클라펫 (유일후보)
|
||||
('(판)클라펫정50(100정)', 'LB000003504', '0232065900005'), # 클라펫 정
|
||||
# 넥스가드 (체중매칭)
|
||||
('넥스가드L(15~30kg)', 'LB000003531', '0232155400009'), # 넥스가드 스펙트라 츄어블 정 대형견용
|
||||
('넥스가드xs(2~3.5kg)', 'LB000003530', '0232169000004'), # 넥스가드 츄어블 정 소형견용
|
||||
# 하트웜 (체중매칭)
|
||||
('하트웜솔루션츄어블M(12~22kg)', 'LB000003155', '0230758520105'), # 하트웜 솔루션 츄어블 0.136mg / 114mg / 6 정
|
||||
('하트웜솔루션츄어블S(11kg이하)', 'LB000003156', '0230758510107'), # 하트웜 솔루션 츄어블 0.068mg / 57mg / 6 정
|
||||
]
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
today = datetime.now().strftime('%Y%m%d')
|
||||
|
||||
print('=== 일괄 APC 매핑 ===\n')
|
||||
|
||||
for name, drugcode, apc in MAPPINGS:
|
||||
# 기존 가격 조회
|
||||
existing = session.execute(text("""
|
||||
SELECT TOP 1 CD_MY_UNIT, CD_IN_UNIT
|
||||
FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = :dc
|
||||
ORDER BY SN DESC
|
||||
"""), {'dc': drugcode}).fetchone()
|
||||
|
||||
if not existing:
|
||||
print(f'❌ {name}: 기존 레코드 없음')
|
||||
continue
|
||||
|
||||
# 이미 APC 있는지 확인
|
||||
check = session.execute(text("""
|
||||
SELECT 1 FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = :dc AND CD_CD_BARCODE = :apc
|
||||
"""), {'dc': drugcode, 'apc': apc}).fetchone()
|
||||
|
||||
if check:
|
||||
print(f'⏭️ {name}: 이미 등록됨')
|
||||
continue
|
||||
|
||||
# INSERT
|
||||
try:
|
||||
session.execute(text("""
|
||||
INSERT INTO CD_ITEM_UNIT_MEMBER (
|
||||
DRUGCODE, CD_CD_UNIT, CD_NM_UNIT, CD_MY_UNIT, CD_IN_UNIT,
|
||||
CD_CD_BARCODE, CD_CD_POS, CHANGE_DATE
|
||||
) VALUES (
|
||||
:drugcode, '015', 1.0, :my_unit, :in_unit,
|
||||
:barcode, '', :change_date
|
||||
)
|
||||
"""), {
|
||||
'drugcode': drugcode,
|
||||
'my_unit': existing.CD_MY_UNIT,
|
||||
'in_unit': existing.CD_IN_UNIT,
|
||||
'barcode': apc,
|
||||
'change_date': today
|
||||
})
|
||||
session.commit()
|
||||
print(f'✅ {name} → {apc}')
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f'❌ {name}: {e}')
|
||||
|
||||
session.close()
|
||||
print('\n완료!')
|
||||
34
backend/scripts/debug_gesidin_match.py
Normal file
@ -0,0 +1,34 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
|
||||
# 테스트 AI 응답
|
||||
ai_response = "개시딘은 피부염 치료에 사용하는 겔 형태의 외용약입니다."
|
||||
|
||||
drug_name = "(판)복합개시딘"
|
||||
|
||||
# 현재 매칭 로직
|
||||
base_name = drug_name.split('(')[0].split('/')[0].strip()
|
||||
print(f'제품명: {drug_name}')
|
||||
print(f'괄호 앞: "{base_name}"')
|
||||
|
||||
# suffix 제거
|
||||
for suffix in ['정', '액', 'L', 'M', 'S', 'XL', 'XS', 'SS', 'mini']:
|
||||
if base_name.endswith(suffix):
|
||||
base_name = base_name[:-len(suffix)]
|
||||
base_name = base_name.strip()
|
||||
print(f'suffix 제거 후: "{base_name}"')
|
||||
|
||||
# 매칭 테스트
|
||||
ai_lower = ai_response.lower()
|
||||
ai_nospace = ai_lower.replace(' ', '')
|
||||
base_lower = base_name.lower()
|
||||
base_nospace = base_lower.replace(' ', '')
|
||||
|
||||
print(f'\n매칭 테스트:')
|
||||
print(f' "{base_lower}" in ai_response? {base_lower in ai_lower}')
|
||||
print(f' "{base_nospace}" in ai_nospace? {base_nospace in ai_nospace}')
|
||||
|
||||
# 문제: (판)이 먼저 잘려서 빈 문자열이 됨!
|
||||
print(f'\n문제: split("(")[0] = "{drug_name.split("(")[0]}"')
|
||||
print('→ "(판)"에서 "("로 시작하니까 빈 문자열!')
|
||||
51
backend/scripts/debug_matching.py
Normal file
@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
# 테스트 AI 응답 (실제 응답 시뮬레이션)
|
||||
ai_response = """
|
||||
네, 안텔민은 개와 고양이 모두 사용 가능합니다!
|
||||
|
||||
**안텔민 킹** - 체중 5kg 이상 반려동물용
|
||||
**안텔민 뽀삐** - 체중 5kg 이하 소형 반려동물용
|
||||
|
||||
두 제품 모두 개와 고양이의 내부 기생충 구제에 효과적입니다.
|
||||
"""
|
||||
|
||||
animal_drugs = [
|
||||
{'name': '안텔민킹(5kg이상)', 'code': 'LB000003157'},
|
||||
{'name': '안텔민뽀삐(5kg이하)', 'code': 'LB000003158'},
|
||||
{'name': '다이로하트정M(12~22kg)', 'code': 'LB000003151'},
|
||||
]
|
||||
|
||||
print('=== 현재 매칭 로직 테스트 ===\n')
|
||||
print(f'AI 응답:\n{ai_response}\n')
|
||||
print('=' * 50)
|
||||
|
||||
ai_response_lower = ai_response.lower()
|
||||
|
||||
for drug in animal_drugs:
|
||||
drug_name = drug['name']
|
||||
base_name = drug_name.split('(')[0].split('/')[0].strip()
|
||||
|
||||
# suffix 제거
|
||||
original_base = base_name
|
||||
for suffix in ['정', '액', 'L', 'M', 'S', 'XL', 'XS', 'SS', 'mini']:
|
||||
if base_name.endswith(suffix):
|
||||
base_name = base_name[:-len(suffix)]
|
||||
base_name = base_name.strip()
|
||||
|
||||
matched = base_name.lower() in ai_response_lower
|
||||
|
||||
print(f'\n제품: {drug_name}')
|
||||
print(f' 괄호 앞: {original_base}')
|
||||
print(f' suffix 제거 후: {base_name}')
|
||||
print(f' 매칭 결과: {"✅ 매칭됨" if matched else "❌ 매칭 안됨"}')
|
||||
|
||||
if not matched:
|
||||
# 왜 안 됐는지 확인
|
||||
print(f' → "{base_name.lower()}" in 응답? {base_name.lower() in ai_response_lower}')
|
||||
# 띄어쓰기 변형 체크
|
||||
spaced = base_name.replace('킹', ' 킹').replace('뽀삐', ' 뽀삐')
|
||||
print(f' → 띄어쓰기 변형 "{spaced.lower()}" in 응답? {spaced.lower() in ai_response_lower}')
|
||||
48
backend/scripts/debug_matching2.py
Normal file
@ -0,0 +1,48 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
# 실제 AI 응답
|
||||
ai_response = """안텔민은 개와 고양이 모두에게 사용할 수 있습니다만, 체중에 따라 복용할 용량이 다릅니다. 🐾
|
||||
|
||||
- **안텔민**: 5kg 이상 개와 고양이에게 복용 가능.
|
||||
- **안텔민 뽀삐**: 5kg 미만 소형 반려동물에게 복용 가능.
|
||||
|
||||
따라서, 반려동물의 체중에 맞는 적절한 제품을 선택해야 해요! 🐶 체중을 알려주시면 더 구체적으로 안내해 드릴 수 있어요."""
|
||||
|
||||
animal_drugs = [
|
||||
{'name': '안텔민', 'code': 'S0000001', 'apc': None},
|
||||
{'name': '안텔민킹(5kg이상)', 'code': 'LB000003157', 'apc': '0230237810109'},
|
||||
{'name': '안텔민뽀삐(5kg이하)', 'code': 'LB000003158', 'apc': '0230237010107'},
|
||||
]
|
||||
|
||||
print('=== 매칭 테스트 ===\n')
|
||||
print(f'AI 응답:\n{ai_response}\n')
|
||||
print('=' * 50)
|
||||
|
||||
ai_response_lower = ai_response.lower()
|
||||
ai_response_nospace = ai_response_lower.replace(' ', '')
|
||||
|
||||
for drug in animal_drugs:
|
||||
drug_name = drug['name']
|
||||
base_name = drug_name.split('(')[0].split('/')[0].strip()
|
||||
|
||||
for suffix in ['정', '액', 'L', 'M', 'S', 'XL', 'XS', 'SS', 'mini']:
|
||||
if base_name.endswith(suffix):
|
||||
base_name = base_name[:-len(suffix)]
|
||||
base_name = base_name.strip()
|
||||
|
||||
base_lower = base_name.lower()
|
||||
base_nospace = base_lower.replace(' ', '')
|
||||
|
||||
in_normal = base_lower in ai_response_lower
|
||||
in_nospace = base_nospace in ai_response_nospace
|
||||
matched = len(base_name) >= 2 and (in_normal or in_nospace)
|
||||
|
||||
print(f'\n제품: {drug_name}')
|
||||
print(f' base_name: "{base_name}"')
|
||||
print(f' base_nospace: "{base_nospace}"')
|
||||
print(f' 일반매칭: {in_normal}')
|
||||
print(f' 공백제거매칭: {in_nospace}')
|
||||
print(f' 최종: {"✅" if matched else "❌"}')
|
||||
43
backend/scripts/debug_prompt.py
Normal file
@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
|
||||
# _get_animal_drugs 로직 복제
|
||||
drug_session = get_db_session('PM_DRUG')
|
||||
query = text("""
|
||||
SELECT
|
||||
G.DrugCode,
|
||||
G.GoodsName,
|
||||
G.Saleprice,
|
||||
(
|
||||
SELECT TOP 1 U.CD_CD_BARCODE
|
||||
FROM CD_ITEM_UNIT_MEMBER U
|
||||
WHERE U.DRUGCODE = G.DrugCode
|
||||
AND U.CD_CD_BARCODE LIKE '023%'
|
||||
ORDER BY U.CHANGE_DATE DESC
|
||||
) AS APC_CODE
|
||||
FROM CD_GOODS G
|
||||
WHERE G.POS_BOON = '010103'
|
||||
AND G.GoodsSelCode = 'B'
|
||||
ORDER BY G.GoodsName
|
||||
""")
|
||||
rows = drug_session.execute(query).fetchall()
|
||||
|
||||
print('=== AI에 전달되는 보유 제품 목록 ===\n')
|
||||
for r in rows:
|
||||
apc = r.APC_CODE
|
||||
rag_info = ""
|
||||
if apc:
|
||||
rag_info = f" [대상: 개, 고양이]" # RAG 정보 시뮬레이션
|
||||
|
||||
print(f"- {r.GoodsName} ({r.Saleprice:,.0f}원){rag_info}")
|
||||
|
||||
print('\n=== 안텔민 관련 제품만 ===')
|
||||
for r in rows:
|
||||
if '안텔민' in r.GoodsName:
|
||||
print(f" {r.GoodsName} - APC: {r.APC_CODE}")
|
||||
42
backend/scripts/debug_rag.py
Normal file
@ -0,0 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
|
||||
|
||||
# 안텔민킹 RAG 정보
|
||||
apc = '0230237810109'
|
||||
print(f'=== 안텔민킹 ({apc}) RAG 정보 ===\n')
|
||||
|
||||
result = pg.execute(text(f"""
|
||||
SELECT
|
||||
product_name,
|
||||
llm_pharm->>'사용가능 동물' as target_animals,
|
||||
llm_pharm->>'분류' as category,
|
||||
llm_pharm->>'체중/부위' as dosage_weight,
|
||||
llm_pharm->>'월령금기' as age_restriction
|
||||
FROM apc
|
||||
WHERE apc = '{apc}'
|
||||
"""))
|
||||
|
||||
row = result.fetchone()
|
||||
if row:
|
||||
print(f'제품명: {row.product_name}')
|
||||
print(f'사용가능 동물: {row.target_animals}')
|
||||
print(f'분류: {row.category}')
|
||||
print(f'체중/용량: {row.dosage_weight}')
|
||||
print(f'월령금기: {row.age_restriction}')
|
||||
|
||||
# efficacy_effect도 확인
|
||||
result2 = pg.execute(text(f"""
|
||||
SELECT efficacy_effect FROM apc WHERE apc = '{apc}'
|
||||
"""))
|
||||
row2 = result2.fetchone()
|
||||
if row2 and row2.efficacy_effect:
|
||||
print(f'\n효능/효과 (원문 일부):')
|
||||
print(row2.efficacy_effect[:500])
|
||||
|
||||
pg.close()
|
||||
86
backend/scripts/debug_rag_prompt.py
Normal file
@ -0,0 +1,86 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text, create_engine
|
||||
|
||||
# 1. _get_animal_drugs 시뮬레이션
|
||||
drug_session = get_db_session('PM_DRUG')
|
||||
query = text("""
|
||||
SELECT
|
||||
G.DrugCode,
|
||||
G.GoodsName,
|
||||
G.Saleprice,
|
||||
(
|
||||
SELECT TOP 1 U.CD_CD_BARCODE
|
||||
FROM CD_ITEM_UNIT_MEMBER U
|
||||
WHERE U.DRUGCODE = G.DrugCode
|
||||
AND U.CD_CD_BARCODE LIKE '023%'
|
||||
ORDER BY U.CHANGE_DATE DESC
|
||||
) AS APC_CODE
|
||||
FROM CD_GOODS G
|
||||
WHERE G.POS_BOON = '010103'
|
||||
AND G.GoodsSelCode = 'B'
|
||||
ORDER BY G.GoodsName
|
||||
""")
|
||||
rows = drug_session.execute(query).fetchall()
|
||||
|
||||
animal_drugs = []
|
||||
for r in rows:
|
||||
animal_drugs.append({
|
||||
'code': r.DrugCode,
|
||||
'name': r.GoodsName,
|
||||
'price': float(r.Saleprice) if r.Saleprice else 0,
|
||||
'apc': r.APC_CODE
|
||||
})
|
||||
|
||||
# 2. _get_animal_drug_rag 시뮬레이션
|
||||
apc_codes = [d['apc'] for d in animal_drugs if d.get('apc')]
|
||||
print(f'APC 코드 목록: {apc_codes}\n')
|
||||
|
||||
rag_data = {}
|
||||
if apc_codes:
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
|
||||
placeholders = ','.join([f"'{apc}'" for apc in apc_codes])
|
||||
result = pg.execute(text(f"""
|
||||
SELECT apc, product_name,
|
||||
llm_pharm->>'사용가능 동물' as target_animals,
|
||||
llm_pharm->>'분류' as category,
|
||||
llm_pharm->>'체중/부위' as dosage_weight,
|
||||
llm_pharm->>'기간/용법' as usage_period,
|
||||
llm_pharm->>'월령금기' as age_restriction
|
||||
FROM apc
|
||||
WHERE apc IN ({placeholders})
|
||||
"""))
|
||||
for row in result:
|
||||
rag_data[row.apc] = {
|
||||
'target_animals': row.target_animals or '정보 없음',
|
||||
'category': row.category or '',
|
||||
'dosage_weight': row.dosage_weight or '',
|
||||
'usage_period': row.usage_period or '',
|
||||
'age_restriction': row.age_restriction or ''
|
||||
}
|
||||
pg.close()
|
||||
|
||||
print(f'RAG 데이터: {rag_data}\n')
|
||||
|
||||
# 3. available_products_text 생성
|
||||
print('=== AI에 전달되는 제품 목록 (RAG 포함) ===\n')
|
||||
for d in animal_drugs:
|
||||
if '안텔민' in d['name']:
|
||||
line = f"- {d['name']} ({d['price']:,.0f}원)"
|
||||
if d.get('apc') and d['apc'] in rag_data:
|
||||
info = rag_data[d['apc']]
|
||||
details = []
|
||||
if info.get('target_animals'):
|
||||
details.append(f"대상: {info['target_animals']}")
|
||||
if info.get('dosage_weight'):
|
||||
details.append(f"용량: {info['dosage_weight']}")
|
||||
if info.get('age_restriction'):
|
||||
details.append(f"금기: {info['age_restriction']}")
|
||||
if details:
|
||||
line += f" [{', '.join(details)}]"
|
||||
print(line)
|
||||
45
backend/scripts/detailed_search.py
Normal file
@ -0,0 +1,45 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
|
||||
|
||||
# 약국 제품 → PostgreSQL 매칭 (체중/용량 포함)
|
||||
mappings = [
|
||||
# (약국제품명, 검색키워드)
|
||||
('제스타제(10정)', '제스타제', '10'),
|
||||
('파라캅L(5kg이상)', '파라캅', 'L'),
|
||||
('파라캅S(5kg이하)', '파라캅', 'S'),
|
||||
('하트캅츄어블(11kg이하)', '하트캅', '11'),
|
||||
('넥스가드L(15~30kg)', '넥스가드', '15'),
|
||||
('넥스가드xs(2~3.5kg)', '넥스가드', '2'),
|
||||
('다이로하트정M(12~22kg)', '다이로하트', '12'),
|
||||
('다이로하트정S(5.6~11kg)', '다이로하트', '5.6'),
|
||||
('다이로하트정SS(5.6kg이하)', '다이로하트', 'SS'),
|
||||
('세레니아정16mg(개멀미약)', '세레니아', '16'),
|
||||
('세레니아정24mg(개멀미약)', '세레니아', '24'),
|
||||
('하트세이버츄어블M(12~22kg)', '하트세이버', '12'),
|
||||
('하트세이버츄어블S(5.6~11kg)', '하트세이버', '5.6'),
|
||||
('하트웜솔루션츄어블M(12~22kg)', '하트웜', '12'),
|
||||
('하트웜솔루션츄어블S(11kg이하)', '하트웜', '11'),
|
||||
]
|
||||
|
||||
print('=== 상세 매칭 검색 ===\n')
|
||||
|
||||
for pharm_name, keyword, size in mappings:
|
||||
result = pg.execute(text("""
|
||||
SELECT apc, product_name, packaging,
|
||||
llm_pharm->>'사용가능 동물' as target
|
||||
FROM apc
|
||||
WHERE product_name ILIKE :kw
|
||||
ORDER BY product_name
|
||||
LIMIT 10
|
||||
"""), {'kw': f'%{keyword}%'})
|
||||
|
||||
print(f'\n📦 {pharm_name} (검색: {keyword}, 사이즈: {size})')
|
||||
for r in result:
|
||||
mark = '⭐' if size.lower() in r.product_name.lower() else ' '
|
||||
print(f'{mark} {r.apc}: {r.product_name[:50]}')
|
||||
|
||||
pg.close()
|
||||
545
backend/scripts/fill_weight_from_dosage.py
Normal file
@ -0,0 +1,545 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
APDB weight_min_kg / weight_max_kg 일괄 채우기
|
||||
- dosage_instructions에서 (사이즈라벨, 체중구간) 쌍을 파싱
|
||||
- APC 레코드의 product_name에 포함된 사이즈 라벨로 매칭
|
||||
|
||||
매칭 전략:
|
||||
1. 제품명에 사이즈 라벨(소형견, 중형견 등)이 있으면 → 해당 체중구간 적용
|
||||
2. 체중 구간이 1개뿐이면 → 전체 APC에 적용
|
||||
3. 다중 구간인데 제품명에 라벨 없으면 → SKIP (안전)
|
||||
|
||||
예외 처리:
|
||||
- 사료/축산 관련(톤당 kg) → SKIP
|
||||
- 축산용(max > 60kg) → SKIP
|
||||
- 체중 구간 파싱 불가 → SKIP
|
||||
|
||||
실행: python scripts/fill_weight_from_dosage.py [--commit] [--verbose]
|
||||
기본: dry-run (DB 변경 없음)
|
||||
--commit: 실제 DB 업데이트 수행
|
||||
--verbose: 상세 로그
|
||||
"""
|
||||
import sys
|
||||
import io
|
||||
import re
|
||||
import argparse
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from sqlalchemy import text, create_engine
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 1. 사이즈 라벨 정의
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
SIZE_LABELS = {
|
||||
'초소형견': 'XS', '초소형': 'XS',
|
||||
'소형견': 'S', '소형': 'S',
|
||||
'중형견': 'M', '중형': 'M',
|
||||
'대형견': 'L', '대형': 'L',
|
||||
'초대형견': 'XL', '초대형': 'XL',
|
||||
}
|
||||
|
||||
# 제품명에서 사이즈 감지용 (긴 것부터 먼저 매칭)
|
||||
PRODUCT_NAME_SIZE_PATTERNS = [
|
||||
(r'초소형견', 'XS'),
|
||||
(r'초소형', 'XS'),
|
||||
(r'소형견', 'S'),
|
||||
(r'소형', 'S'),
|
||||
(r'중형견', 'M'),
|
||||
(r'중형', 'M'),
|
||||
(r'초대형견', 'XL'),
|
||||
(r'초대형', 'XL'),
|
||||
(r'대형견', 'L'),
|
||||
(r'대형', 'L'),
|
||||
# 영문/약어
|
||||
(r'\bSS\b', 'XS'),
|
||||
(r'\bXS\b', 'XS'),
|
||||
(r'[-\s]S\b', 'S'),
|
||||
(r'\bS\(', 'S'),
|
||||
(r'[-\s]M\b', 'M'),
|
||||
(r'\bM\(', 'M'),
|
||||
(r'[-\s]L\b', 'L'),
|
||||
(r'\bL\(', 'L'),
|
||||
(r'\bXL\b', 'XL'),
|
||||
]
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 2. 체중 구간 파싱
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def strip_html(html_text):
|
||||
"""HTML 태그 제거, 줄 단위 텍스트 반환"""
|
||||
if not html_text:
|
||||
return ""
|
||||
t = html_text.replace('<p class="indent0">', '\n').replace('</p>', '')
|
||||
t = re.sub(r'<[^>]+>', '', t)
|
||||
return t
|
||||
|
||||
|
||||
def is_livestock_context(text_content):
|
||||
"""축산/사료 관련인지 판단"""
|
||||
# 톤당 kg은 사료 관련
|
||||
if '톤당' in text_content and 'kg' in text_content:
|
||||
# 체중 구간이 별도로 있는 경우는 반려동물일 수 있음
|
||||
if '체중' not in text_content and '형견' not in text_content:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def parse_weight_ranges(dosage_instructions):
|
||||
"""
|
||||
dosage_instructions에서 (사이즈라벨, 체중min, 체중max) 리스트를 추출.
|
||||
체중 구간만 추출하며, 성분 용량은 무시.
|
||||
|
||||
Returns:
|
||||
list of dict: [{'min': 0, 'max': 11, 'size': 'S', 'label': '소형견'}, ...]
|
||||
"""
|
||||
if not dosage_instructions:
|
||||
return []
|
||||
|
||||
txt = strip_html(dosage_instructions)
|
||||
|
||||
# 축산/사료 관련 제외
|
||||
if is_livestock_context(txt):
|
||||
return []
|
||||
|
||||
ranges = []
|
||||
seen = set() # (size, min, max) 중복 방지
|
||||
|
||||
# ── 전처리: 줄 분리된 사이즈+체중 합치기 ──
|
||||
# HTML 변환 후 빈 줄이 끼어있을 수 있음:
|
||||
# "소형견 1chewable 68㎍ 57mg\n\n(체중0-11kg)"
|
||||
# → "소형견 1chewable 68㎍ 57mg (체중0-11kg)"
|
||||
lines = txt.split('\n')
|
||||
# 빈 줄 제거한 리스트 (인덱스 보존)
|
||||
non_empty = [(i, line.strip()) for i, line in enumerate(lines) if line.strip()]
|
||||
|
||||
merged_set = set() # 합쳐진 줄 인덱스 (원본 기준)
|
||||
merged_lines = []
|
||||
|
||||
for idx, (orig_i, stripped) in enumerate(non_empty):
|
||||
if orig_i in merged_set:
|
||||
continue
|
||||
# 현재 줄에 사이즈 라벨이 있고, 다음 비어있지 않은 줄이 (체중...) 패턴이면 합치기
|
||||
if idx + 1 < len(non_empty):
|
||||
next_orig_i, next_stripped = non_empty[idx + 1]
|
||||
if (re.match(r'\(체중', next_stripped)
|
||||
and re.search(r'(초소형|소형|중형|대형|초대형)견?', stripped)):
|
||||
merged_lines.append(stripped + ' ' + next_stripped)
|
||||
merged_set.add(next_orig_i)
|
||||
continue
|
||||
merged_lines.append(stripped)
|
||||
|
||||
txt = '\n'.join(merged_lines)
|
||||
|
||||
def add_range(size, wmin, wmax, label):
|
||||
"""중복 방지하며 범위 추가"""
|
||||
if wmax > 60: # 반려동물 체중 범위 초과 → 축산용
|
||||
return
|
||||
if wmax <= wmin:
|
||||
return
|
||||
key = (size, wmin, wmax)
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
ranges.append({'min': wmin, 'max': wmax, 'size': size, 'label': label})
|
||||
|
||||
def get_size(label_text):
|
||||
"""라벨 텍스트 → 사이즈 코드"""
|
||||
return SIZE_LABELS.get(label_text + '견', SIZE_LABELS.get(label_text))
|
||||
|
||||
# ── 패턴1: "X형견(체중A-Bkg)" / "X형견 ... (체중A-Bkg)" ──
|
||||
# 예: "소형견(체중0-11kg)", "중형견(체중12-22kg)"
|
||||
# 예(줄 합침): "소형견 1chewable 68㎍ 57mg (체중0-11kg)"
|
||||
for m in re.finditer(
|
||||
r'(초소형|소형|중형|대형|초대형)견?\s*(?:용\s*)?\(?(?:체중\s*)?'
|
||||
r'(\d+\.?\d*)\s*[-~~]\s*(\d+\.?\d*)\s*kg',
|
||||
txt
|
||||
):
|
||||
label = m.group(1)
|
||||
add_range(get_size(label), float(m.group(2)), float(m.group(3)), label + '견')
|
||||
|
||||
# ── 패턴1b: 같은 줄에 라벨과 (체중...)이 먼 경우 ──
|
||||
# 예: "소형견 1chewable 68㎍ 57mg 1개월 (체중0-11kg)"
|
||||
for m in re.finditer(
|
||||
r'(초소형|소형|중형|대형|초대형)견?\b[^\n]*?\(체중\s*'
|
||||
r'(\d+\.?\d*)\s*[-~~]\s*(\d+\.?\d*)\s*kg\)',
|
||||
txt
|
||||
):
|
||||
label = m.group(1)
|
||||
add_range(get_size(label), float(m.group(2)), float(m.group(3)), label + '견')
|
||||
|
||||
# ── 패턴2: "체중A~Bkg X형견용" ──
|
||||
# 예: "체중12~22kg 중형견용(M)"
|
||||
for m in re.finditer(
|
||||
r'(?:체중\s*)?(\d+\.?\d*)\s*[-~~]\s*(\d+\.?\d*)\s*kg\s*(?:의\s*)?'
|
||||
r'(초소형|소형|중형|대형|초대형)견?',
|
||||
txt
|
||||
):
|
||||
label = m.group(3)
|
||||
add_range(get_size(label), float(m.group(1)), float(m.group(2)), label + '견')
|
||||
|
||||
# ── 패턴3: "Akg이하 X형견" / "~Akg X형견" ──
|
||||
# 예: "11kg이하 소형견용"
|
||||
for m in re.finditer(
|
||||
r'(?:체중\s*)?[~~]?\s*(\d+\.?\d*)\s*kg\s*(?:이하|까지)?\s*(?:의\s*)?'
|
||||
r'(초소형|소형|중형|대형|초대형)견?',
|
||||
txt
|
||||
):
|
||||
label = m.group(2)
|
||||
add_range(get_size(label), 0, float(m.group(1)), label + '견')
|
||||
|
||||
# ── 패턴4: "(Akg~Bkg의 X형견에게)" ──
|
||||
# 예: "(5.7kg ~11kg의 소형견에게 본제 1정 투여)"
|
||||
for m in re.finditer(
|
||||
r'\(\s*(\d+\.?\d*)\s*kg?\s*[-~~]\s*(\d+\.?\d*)\s*kg\s*(?:의\s*)?'
|
||||
r'(초소형|소형|중형|대형|초대형)견',
|
||||
txt
|
||||
):
|
||||
label = m.group(3)
|
||||
add_range(get_size(label), float(m.group(1)), float(m.group(2)), label + '견')
|
||||
|
||||
# ── 패턴4b: "(Akg.Bkg의 X형견에게)" - 마침표 구분자 ──
|
||||
# 예: "(12kg.22kg의 중형견에게)"
|
||||
for m in re.finditer(
|
||||
r'\(\s*(\d+\.?\d*)\s*kg\s*\.\s*(\d+\.?\d*)\s*kg\s*(?:의\s*)?'
|
||||
r'(초소형|소형|중형|대형|초대형)견',
|
||||
txt
|
||||
):
|
||||
label = m.group(3)
|
||||
add_range(get_size(label), float(m.group(1)), float(m.group(2)), label + '견')
|
||||
|
||||
# ── 패턴5: "Akg이하의 X형견에게" ──
|
||||
# 예: "(5.6kg이하의 초소형견에게)"
|
||||
for m in re.finditer(
|
||||
r'(\d+\.?\d*)\s*kg\s*이하\s*(?:의\s*)?(초소형|소형|중형|대형|초대형)견',
|
||||
txt
|
||||
):
|
||||
label = m.group(2)
|
||||
add_range(get_size(label), 0, float(m.group(1)), label + '견')
|
||||
|
||||
# ── 패턴6: 테이블 "A~B | 제품명 X형견용" ──
|
||||
# 예: "2~3.5 넥스가드 스펙트라 츄어블 초소형견용 1"
|
||||
# 예: "2-5 | 프론트라인 트리액트 초소형견용 | 0.5ml"
|
||||
for m in re.finditer(
|
||||
r'(\d+\.?\d*)\s*[-~~]\s*(\d+\.?\d*)\s*[\s|]*[^\n]*?'
|
||||
r'(초소형|소형|중형|대형|초대형)견?용?',
|
||||
txt
|
||||
):
|
||||
label = m.group(3)
|
||||
wmin, wmax = float(m.group(1)), float(m.group(2))
|
||||
if wmax <= 60:
|
||||
add_range(get_size(label), wmin, wmax, label + '견')
|
||||
|
||||
# ── 패턴7: "체중 Akg 미만 X형견용" ──
|
||||
# 예: "체중 15kg 미만 소, 중형견용"
|
||||
for m in re.finditer(
|
||||
r'체중\s*(\d+\.?\d*)\s*kg\s*미만\s*[^\n]*?'
|
||||
r'(초소형|소형|중형|대형|초대형)견',
|
||||
txt
|
||||
):
|
||||
label = m.group(2)
|
||||
add_range(get_size(label), 0, float(m.group(1)), label + '견')
|
||||
|
||||
# ── 패턴8: 라벨 없이 체중 구간만 (반려동물 키워드 있을 때) ──
|
||||
if not ranges and ('개' in txt or '고양이' in txt or '반려' in txt or '애완' in txt):
|
||||
# 8a: "Xkg 초과-Ykg 이하" / "Xkg 초과 ~ Ykg" (먼저 처리)
|
||||
for m in re.finditer(
|
||||
r'(\d+\.?\d*)\s*kg\s*초과\s*[-~~]?\s*(\d+\.?\d*)\s*kg(?:\s*(?:이하|까지))?',
|
||||
txt
|
||||
):
|
||||
wmin, wmax = float(m.group(1)), float(m.group(2))
|
||||
if wmax <= 60 and wmax > wmin:
|
||||
add_range(None, wmin, wmax, None)
|
||||
|
||||
# 8b: "X-Ykg" / "X~Ykg" 일반 범위
|
||||
for m in re.finditer(
|
||||
r'(?:체중\s*)?(\d+\.?\d*)\s*[-~~]\s*(\d+\.?\d*)\s*kg',
|
||||
txt
|
||||
):
|
||||
wmin, wmax = float(m.group(1)), float(m.group(2))
|
||||
if wmax <= 60 and wmax > wmin:
|
||||
add_range(None, wmin, wmax, None)
|
||||
|
||||
# 8c: "Xkg 이하" / "~Xkg" (최소=0)
|
||||
# 단, "Akg 초과-Xkg 이하"는 8a에서 이미 처리되었으므로 제외
|
||||
for m in re.finditer(
|
||||
r'(?:체중\s*)?[~~]\s*(\d+\.?\d*)\s*kg|(\d+\.?\d*)\s*kg\s*(?:이하|까지)',
|
||||
txt
|
||||
):
|
||||
val = m.group(1) or m.group(2)
|
||||
wmax = float(val)
|
||||
if wmax <= 60:
|
||||
# "초과-Xkg 이하" 컨텍스트인지 확인 → 이미 8a에서 처리됨
|
||||
start = max(0, m.start() - 15)
|
||||
before = txt[start:m.start()]
|
||||
if '초과' in before:
|
||||
continue
|
||||
add_range(None, 0, wmax, None)
|
||||
|
||||
# 정렬 (min 기준)
|
||||
ranges.sort(key=lambda x: x['min'])
|
||||
return ranges
|
||||
|
||||
|
||||
def is_multi_size_product_name(product_name):
|
||||
"""
|
||||
제품명에 여러 사이즈가 함께 들어있는 통합 제품인지 판단.
|
||||
예: "하트커버(SS,S,M,L)정" → True
|
||||
"""
|
||||
if not product_name:
|
||||
return False
|
||||
# 여러 사이즈 약어가 한 제품명에 있는 경우
|
||||
if re.search(r'[(\(].*(?:SS|XS).*[,/].*(?:S|M|L).*[)\)]', product_name):
|
||||
return True
|
||||
# 소형/중형/대형 등이 2개 이상 포함된 경우
|
||||
size_count = sum(1 for kw in ['초소형', '소형', '중형', '대형', '초대형']
|
||||
if kw in product_name)
|
||||
if size_count >= 2:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def detect_size_from_product_name(product_name):
|
||||
"""
|
||||
제품명에서 사이즈 라벨을 감지.
|
||||
Returns: 'XS', 'S', 'M', 'L', 'XL' 또는 None
|
||||
통합 제품(SS,S,M,L 등 여러 사이즈)은 None 반환.
|
||||
"""
|
||||
if not product_name:
|
||||
return None
|
||||
# 통합 제품 제외
|
||||
if is_multi_size_product_name(product_name):
|
||||
return None
|
||||
for pattern, size in PRODUCT_NAME_SIZE_PATTERNS:
|
||||
if re.search(pattern, product_name):
|
||||
return size
|
||||
return None
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# 3. 메인 로직
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='APDB weight_min_kg/weight_max_kg 일괄 채우기')
|
||||
parser.add_argument('--commit', action='store_true', help='실제 DB 업데이트 수행 (기본: dry-run)')
|
||||
parser.add_argument('--verbose', '-v', action='store_true', help='상세 로그')
|
||||
args = parser.parse_args()
|
||||
|
||||
dry_run = not args.commit
|
||||
|
||||
if dry_run:
|
||||
print("=" * 60)
|
||||
print(" DRY-RUN 모드 (DB 변경 없음)")
|
||||
print(" 실제 업데이트: python scripts/fill_weight_from_dosage.py --commit")
|
||||
print("=" * 60)
|
||||
else:
|
||||
print("=" * 60)
|
||||
print(" COMMIT 모드 - DB에 실제 업데이트합니다")
|
||||
print("=" * 60)
|
||||
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master')
|
||||
conn = pg.connect()
|
||||
|
||||
# ── 동물용의약품 중 dosage_instructions에 kg 있고 weight 미입력인 APC 전체 조회 ──
|
||||
apcs = conn.execute(text('''
|
||||
SELECT apc, item_seq, product_name, dosage, dosage_instructions,
|
||||
product_type
|
||||
FROM apc
|
||||
WHERE product_type = '동물용의약품'
|
||||
AND dosage_instructions ILIKE '%%kg%%'
|
||||
AND weight_min_kg IS NULL
|
||||
ORDER BY item_seq, apc
|
||||
''')).fetchall()
|
||||
|
||||
print(f'\n대상 APC 레코드: {len(apcs)}건')
|
||||
|
||||
# item_seq별로 그룹핑
|
||||
from collections import defaultdict
|
||||
items = defaultdict(list)
|
||||
di_cache = {}
|
||||
for row in apcs:
|
||||
items[row.item_seq].append(row)
|
||||
if row.item_seq not in di_cache:
|
||||
di_cache[row.item_seq] = row.dosage_instructions
|
||||
|
||||
print(f'대상 item_seq: {len(items)}건\n')
|
||||
|
||||
stats = {
|
||||
'total_items': len(items),
|
||||
'updated': 0,
|
||||
'matched_by_name': 0,
|
||||
'matched_by_dosage_order': 0,
|
||||
'matched_single': 0,
|
||||
'skipped_no_parse': 0,
|
||||
'skipped_livestock': 0,
|
||||
'skipped_multi_no_label': 0,
|
||||
}
|
||||
|
||||
updates = [] # (apc, weight_min, weight_max, product_name, reason)
|
||||
|
||||
for item_seq, apc_rows in items.items():
|
||||
di = di_cache[item_seq]
|
||||
first_name = apc_rows[0].product_name
|
||||
|
||||
# 체중 구간 파싱
|
||||
weight_ranges = parse_weight_ranges(di)
|
||||
|
||||
if not weight_ranges:
|
||||
stats['skipped_no_parse'] += 1
|
||||
if args.verbose:
|
||||
print(f' SKIP (파싱불가): {first_name} ({item_seq})')
|
||||
continue
|
||||
|
||||
# 축산용 필터 (max > 60kg인 구간이 있으면 전체 SKIP)
|
||||
if any(r['max'] > 60 for r in weight_ranges):
|
||||
stats['skipped_livestock'] += 1
|
||||
if args.verbose:
|
||||
large = [r for r in weight_ranges if r['max'] > 60]
|
||||
print(f' SKIP (축산용): {first_name} ({item_seq}) max={large[0]["max"]}kg')
|
||||
continue
|
||||
|
||||
if len(weight_ranges) == 1:
|
||||
# ── 체중 구간 1개 → 전체 APC에 적용 ──
|
||||
wr = weight_ranges[0]
|
||||
for row in apc_rows:
|
||||
updates.append((row.apc, wr['min'], wr['max'], row.product_name, '단일구간'))
|
||||
stats['matched_single'] += len(apc_rows)
|
||||
stats['updated'] += len(apc_rows)
|
||||
if args.verbose:
|
||||
print(f' 적용 (단일구간): {first_name} → {wr["min"]}~{wr["max"]}kg ({len(apc_rows)}건)')
|
||||
|
||||
else:
|
||||
# ── 체중 구간 여러 개 → 제품명의 사이즈 라벨로 매칭 ──
|
||||
size_to_weight = {}
|
||||
for wr in weight_ranges:
|
||||
if wr['size']:
|
||||
size_to_weight[wr['size']] = (wr['min'], wr['max'])
|
||||
|
||||
# 먼저 제품명 라벨로 매칭 시도
|
||||
unmatched_rows = []
|
||||
for row in apc_rows:
|
||||
size = detect_size_from_product_name(row.product_name)
|
||||
if size and size in size_to_weight:
|
||||
wmin, wmax = size_to_weight[size]
|
||||
updates.append((row.apc, wmin, wmax, row.product_name, f'제품명→{size}'))
|
||||
stats['matched_by_name'] += 1
|
||||
stats['updated'] += 1
|
||||
if args.verbose:
|
||||
print(f' 적용 (제품명 {size}): {row.product_name} → {wmin}~{wmax}kg')
|
||||
else:
|
||||
unmatched_rows.append(row)
|
||||
|
||||
# ── 제품명 매칭 실패한 것들 → dosage 순서 매칭 시도 ──
|
||||
if unmatched_rows:
|
||||
# dosage 값이 있는 APC만 추출 (NaN 제외)
|
||||
rows_with_dosage = [r for r in unmatched_rows
|
||||
if r.dosage and r.dosage != 'NaN']
|
||||
rows_no_dosage = [r for r in unmatched_rows
|
||||
if not r.dosage or r.dosage == 'NaN']
|
||||
|
||||
if rows_with_dosage and len(weight_ranges) >= 2:
|
||||
# dosage에서 첫 번째 숫자 추출하여 정렬 키로 사용
|
||||
def dosage_sort_key(dosage_str):
|
||||
nums = re.findall(r'(\d+\.?\d+)', dosage_str)
|
||||
return float(nums[0]) if nums else 0
|
||||
|
||||
# 고유 dosage 값 추출 (순서 유지)
|
||||
unique_dosages = sorted(
|
||||
set(r.dosage for r in rows_with_dosage),
|
||||
key=dosage_sort_key
|
||||
)
|
||||
# 체중 구간도 min 기준 정렬 (이미 정렬됨)
|
||||
sorted_ranges = sorted(weight_ranges, key=lambda x: x['min'])
|
||||
|
||||
if len(unique_dosages) == len(sorted_ranges):
|
||||
# 개수 일치 → 순서 매칭 (작은 용량 = 작은 체중)
|
||||
dosage_to_weight = {}
|
||||
for d, wr in zip(unique_dosages, sorted_ranges):
|
||||
dosage_to_weight[d] = (wr['min'], wr['max'])
|
||||
|
||||
for row in rows_with_dosage:
|
||||
if row.dosage in dosage_to_weight:
|
||||
wmin, wmax = dosage_to_weight[row.dosage]
|
||||
updates.append((row.apc, wmin, wmax, row.product_name,
|
||||
f'dosage순서→{wmin}~{wmax}'))
|
||||
stats['matched_by_dosage_order'] += 1
|
||||
stats['updated'] += 1
|
||||
if args.verbose:
|
||||
print(f' 적용 (dosage순서): {row.product_name} '
|
||||
f'dosage={row.dosage} → {wmin}~{wmax}kg')
|
||||
else:
|
||||
stats['skipped_multi_no_label'] += 1
|
||||
if args.verbose:
|
||||
print(f' SKIP (dosage매칭실패): {row.product_name}')
|
||||
|
||||
# dosage 없는 APC (대표 품목 등)
|
||||
for row in rows_no_dosage:
|
||||
stats['skipped_multi_no_label'] += 1
|
||||
if args.verbose:
|
||||
print(f' SKIP (다중구간+dosage없음): {row.product_name}')
|
||||
|
||||
if args.verbose and dosage_to_weight:
|
||||
print(f' dosage 매핑: {dict((d, f"{w[0]}~{w[1]}kg") for d, w in dosage_to_weight.items())}')
|
||||
else:
|
||||
# 개수 불일치 → SKIP
|
||||
for row in unmatched_rows:
|
||||
stats['skipped_multi_no_label'] += 1
|
||||
if args.verbose:
|
||||
print(f' SKIP (dosage수≠구간수): {row.product_name} '
|
||||
f'(dosage {len(unique_dosages)}종 vs 구간 {len(sorted_ranges)}개)')
|
||||
else:
|
||||
# dosage 없는 APC만 남음
|
||||
for row in unmatched_rows:
|
||||
stats['skipped_multi_no_label'] += 1
|
||||
if args.verbose:
|
||||
print(f' SKIP (다중구간+라벨없음): {row.product_name} '
|
||||
f'(감지={detect_size_from_product_name(row.product_name)}, '
|
||||
f'가용={list(size_to_weight.keys())})')
|
||||
|
||||
# ── 결과 출력 ──
|
||||
print('\n' + '=' * 60)
|
||||
print(' 결과 요약')
|
||||
print('=' * 60)
|
||||
print(f' 대상 item_seq: {stats["total_items"]}건')
|
||||
print(f' 업데이트할 APC: {stats["updated"]}건')
|
||||
print(f' - 단일구간 적용: {stats["matched_single"]}건')
|
||||
print(f' - 제품명 라벨 매칭: {stats["matched_by_name"]}건')
|
||||
print(f' - dosage 순서 매칭: {stats["matched_by_dosage_order"]}건')
|
||||
print(f' SKIP - 파싱 불가: {stats["skipped_no_parse"]}건')
|
||||
print(f' SKIP - 축산용 (>60kg): {stats["skipped_livestock"]}건')
|
||||
print(f' SKIP - 다중구간+라벨없음: {stats["skipped_multi_no_label"]}건')
|
||||
|
||||
if updates:
|
||||
print(f'\n === 업데이트 미리보기 (처음 30건) ===')
|
||||
for apc, wmin, wmax, pname, reason in updates[:30]:
|
||||
print(f' {apc} | {pname[:35]:35s} → {wmin}~{wmax}kg [{reason}]')
|
||||
if len(updates) > 30:
|
||||
print(f' ... 외 {len(updates) - 30}건')
|
||||
|
||||
# ── DB 업데이트 ──
|
||||
if not dry_run and updates:
|
||||
print(f'\n DB 업데이트 시작...')
|
||||
conn.close()
|
||||
with pg.begin() as tx_conn:
|
||||
for apc_code, wmin, wmax, _, _ in updates:
|
||||
tx_conn.execute(text('''
|
||||
UPDATE apc
|
||||
SET weight_min_kg = :wmin, weight_max_kg = :wmax
|
||||
WHERE apc = :apc
|
||||
'''), {'wmin': wmin, 'wmax': wmax, 'apc': apc_code})
|
||||
print(f' 완료: {len(updates)}건 업데이트')
|
||||
elif not dry_run and not updates:
|
||||
print('\n 업데이트할 항목이 없습니다.')
|
||||
conn.close()
|
||||
else:
|
||||
conn.close()
|
||||
print('\n완료.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
23
backend/scripts/fix_gesidin_boon.py
Normal file
@ -0,0 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
|
||||
print('업데이트 전:')
|
||||
r = session.execute(text("SELECT GoodsName, POS_BOON FROM CD_GOODS WHERE DrugCode = 'LB000003140'")).fetchone()
|
||||
print(f' {r.GoodsName}: POS_BOON = {r.POS_BOON}')
|
||||
|
||||
session.execute(text("UPDATE CD_GOODS SET POS_BOON = '010103' WHERE DrugCode = 'LB000003140'"))
|
||||
session.commit()
|
||||
|
||||
print('\n업데이트 후:')
|
||||
r2 = session.execute(text("SELECT GoodsName, POS_BOON FROM CD_GOODS WHERE DrugCode = 'LB000003140'")).fetchone()
|
||||
print(f' {r2.GoodsName}: POS_BOON = {r2.POS_BOON}')
|
||||
print(' ✅ 완료!')
|
||||
|
||||
session.close()
|
||||
75
backend/scripts/insert_apc_gesidin.py
Normal file
@ -0,0 +1,75 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
from datetime import datetime
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
|
||||
# 1. 기존 데이터에서 가격 정보 가져오기
|
||||
print('1. 기존 레코드에서 가격 정보 조회...')
|
||||
existing = session.execute(text("""
|
||||
SELECT TOP 1 CD_MY_UNIT, CD_IN_UNIT
|
||||
FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = 'LB000003140'
|
||||
ORDER BY SN DESC
|
||||
""")).fetchone()
|
||||
|
||||
sale_price = existing.CD_MY_UNIT
|
||||
purchase_price = existing.CD_IN_UNIT
|
||||
print(f' 판매가: {sale_price:,.0f}원')
|
||||
print(f' 입고가: {purchase_price:,.0f}원')
|
||||
|
||||
# 2. 오늘 날짜
|
||||
today = datetime.now().strftime('%Y%m%d')
|
||||
print(f'\n2. 날짜: {today}')
|
||||
|
||||
# 3. INSERT 실행
|
||||
print('\n3. INSERT 실행...')
|
||||
apc_code = '0231093520106' # 복합개시딘 10g
|
||||
|
||||
try:
|
||||
session.execute(text("""
|
||||
INSERT INTO CD_ITEM_UNIT_MEMBER (
|
||||
DRUGCODE, CD_CD_UNIT, CD_NM_UNIT, CD_MY_UNIT, CD_IN_UNIT,
|
||||
CD_CD_BARCODE, CD_CD_POS, CHANGE_DATE
|
||||
) VALUES (
|
||||
:drugcode, :unit, :nm_unit, :my_unit, :in_unit,
|
||||
:barcode, :pos, :change_date
|
||||
)
|
||||
"""), {
|
||||
'drugcode': 'LB000003140',
|
||||
'unit': '015',
|
||||
'nm_unit': 1.0,
|
||||
'my_unit': sale_price,
|
||||
'in_unit': purchase_price,
|
||||
'barcode': apc_code,
|
||||
'pos': '',
|
||||
'change_date': today
|
||||
})
|
||||
|
||||
session.commit()
|
||||
print(f' ✅ 성공! APC {apc_code} 추가됨')
|
||||
|
||||
# 4. 확인
|
||||
print('\n4. 결과 확인...')
|
||||
result = session.execute(text("""
|
||||
SELECT DRUGCODE, CD_CD_BARCODE, CD_MY_UNIT, SN
|
||||
FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = 'LB000003140' AND CD_CD_BARCODE = :apc
|
||||
"""), {'apc': apc_code})
|
||||
|
||||
row = result.fetchone()
|
||||
if row:
|
||||
print(f' DRUGCODE: {row.DRUGCODE}')
|
||||
print(f' BARCODE: {row.CD_CD_BARCODE}')
|
||||
print(f' SN: {row.SN}')
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f' ❌ 실패: {e}')
|
||||
|
||||
session.close()
|
||||
90
backend/scripts/insert_apc_poppy.py
Normal file
@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
안텔민뽀삐 APC 추가 실행 (SN 자동 생성)
|
||||
"""
|
||||
import sys
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
from datetime import datetime
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
|
||||
# 1. 기존 데이터에서 가격 정보 가져오기
|
||||
print('1. 기존 레코드에서 가격 정보 조회...')
|
||||
existing = session.execute(text("""
|
||||
SELECT TOP 1 CD_MY_UNIT, CD_IN_UNIT
|
||||
FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = 'LB000003158'
|
||||
ORDER BY SN DESC
|
||||
""")).fetchone()
|
||||
|
||||
sale_price = existing.CD_MY_UNIT
|
||||
purchase_price = existing.CD_IN_UNIT
|
||||
print(f' 판매가: {sale_price:,.0f}원')
|
||||
print(f' 입고가: {purchase_price:,.0f}원')
|
||||
|
||||
# 2. 오늘 날짜
|
||||
today = datetime.now().strftime('%Y%m%d')
|
||||
print(f'\n2. 날짜: {today}')
|
||||
|
||||
# 3. INSERT 실행 (SN은 IDENTITY 자동 생성)
|
||||
print('\n3. INSERT 실행...')
|
||||
apc_code = '0230237010107' # 안텔민뽀삐 10정
|
||||
|
||||
try:
|
||||
session.execute(text("""
|
||||
INSERT INTO CD_ITEM_UNIT_MEMBER (
|
||||
DRUGCODE,
|
||||
CD_CD_UNIT,
|
||||
CD_NM_UNIT,
|
||||
CD_MY_UNIT,
|
||||
CD_IN_UNIT,
|
||||
CD_CD_BARCODE,
|
||||
CD_CD_POS,
|
||||
CHANGE_DATE
|
||||
) VALUES (
|
||||
:drugcode,
|
||||
:unit,
|
||||
:nm_unit,
|
||||
:my_unit,
|
||||
:in_unit,
|
||||
:barcode,
|
||||
:pos,
|
||||
:change_date
|
||||
)
|
||||
"""), {
|
||||
'drugcode': 'LB000003158',
|
||||
'unit': '015',
|
||||
'nm_unit': 1.0,
|
||||
'my_unit': sale_price,
|
||||
'in_unit': purchase_price,
|
||||
'barcode': apc_code,
|
||||
'pos': '',
|
||||
'change_date': today
|
||||
})
|
||||
|
||||
session.commit()
|
||||
print(f' ✅ 성공! APC {apc_code} 추가됨')
|
||||
|
||||
# 4. 확인
|
||||
print('\n4. 결과 확인...')
|
||||
result = session.execute(text("""
|
||||
SELECT * FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = 'LB000003158' AND CD_CD_BARCODE = :apc
|
||||
"""), {'apc': apc_code})
|
||||
|
||||
row = result.fetchone()
|
||||
if row:
|
||||
print(' --- 추가된 레코드 ---')
|
||||
for col in result.keys():
|
||||
print(f' {col}: {getattr(row, col)}')
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f' ❌ 실패: {e}')
|
||||
|
||||
session.close()
|
||||
36
backend/scripts/list_petfarm.py
Normal file
@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
|
||||
print('=== 펫팜 공급 동물약 ===\n')
|
||||
result = session.execute(text("""
|
||||
SELECT
|
||||
G.DrugCode,
|
||||
G.GoodsName,
|
||||
G.POS_BOON,
|
||||
S.SplName,
|
||||
(
|
||||
SELECT TOP 1 U.CD_CD_BARCODE
|
||||
FROM CD_ITEM_UNIT_MEMBER U
|
||||
WHERE U.DRUGCODE = G.DrugCode
|
||||
AND U.CD_CD_BARCODE LIKE '023%'
|
||||
) AS APC_CODE
|
||||
FROM CD_GOODS G
|
||||
LEFT JOIN CD_SALEGOODS S ON G.DrugCode = S.DrugCode
|
||||
WHERE S.SplName LIKE N'%펫팜%'
|
||||
ORDER BY G.GoodsName
|
||||
"""))
|
||||
|
||||
for row in result:
|
||||
apc_status = f'✅ {row.APC_CODE}' if row.APC_CODE else '❌ 없음'
|
||||
boon_status = '🐾' if row.POS_BOON == '010103' else ' '
|
||||
print(f'{boon_status} {row.GoodsName}')
|
||||
print(f' APC: {apc_status}')
|
||||
|
||||
session.close()
|
||||
68
backend/scripts/perf_test.py
Normal file
@ -0,0 +1,68 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""APC 매칭 성능 측정"""
|
||||
import sys, io, time
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text, create_engine
|
||||
|
||||
print('=== APC 매칭 성능 측정 ===\n')
|
||||
|
||||
# 1. MSSQL: 동물약 + APC 조회
|
||||
start = time.time()
|
||||
session = get_db_session('PM_DRUG')
|
||||
result = session.execute(text("""
|
||||
SELECT G.DrugCode, G.GoodsName,
|
||||
(SELECT TOP 1 U.CD_CD_BARCODE FROM CD_ITEM_UNIT_MEMBER U
|
||||
WHERE U.DRUGCODE = G.DrugCode AND U.CD_CD_BARCODE LIKE '023%') AS APC_CODE
|
||||
FROM CD_GOODS G
|
||||
WHERE G.POS_BOON = '010103' AND G.GoodsSelCode = 'B'
|
||||
"""))
|
||||
mssql_rows = list(result)
|
||||
no_apc = [r for r in mssql_rows if not r.APC_CODE]
|
||||
has_apc = [r for r in mssql_rows if r.APC_CODE]
|
||||
mssql_time = time.time() - start
|
||||
print(f'1. MSSQL 동물약 조회: {mssql_time:.3f}초')
|
||||
print(f' - 총 제품: {len(mssql_rows)}개')
|
||||
print(f' - APC 있음: {len(has_apc)}개 ✅')
|
||||
print(f' - APC 없음: {len(no_apc)}개 ❌')
|
||||
|
||||
# 2. PostgreSQL 연결 + 매칭 검색
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
|
||||
|
||||
# 샘플 매칭 테스트
|
||||
sample_count = min(5, len(no_apc))
|
||||
start = time.time()
|
||||
match_count = 0
|
||||
for drug in no_apc[:sample_count]:
|
||||
search_name = drug.GoodsName.replace('(판)', '').split('(')[0].strip()
|
||||
res = pg.execute(text("""
|
||||
SELECT apc, product_name FROM apc
|
||||
WHERE product_name ILIKE :p LIMIT 5
|
||||
"""), {'p': f'%{search_name}%'})
|
||||
if list(res):
|
||||
match_count += 1
|
||||
pg_search_time = time.time() - start
|
||||
per_search = pg_search_time / sample_count if sample_count > 0 else 0
|
||||
print(f'\n2. PostgreSQL 매칭 검색: {pg_search_time:.3f}초 ({sample_count}개 샘플)')
|
||||
print(f' - 건당 소요: {per_search*1000:.1f}ms')
|
||||
print(f' - 매칭 성공: {match_count}/{sample_count}')
|
||||
print(f' - 예상 전체: {per_search * len(no_apc):.1f}초 ({len(no_apc)}개)')
|
||||
|
||||
# 3. APC 테이블 통계
|
||||
start = time.time()
|
||||
total_apc = pg.execute(text("SELECT COUNT(*) FROM apc")).scalar()
|
||||
with_image = pg.execute(text("SELECT COUNT(*) FROM apc WHERE image_url1 IS NOT NULL AND image_url1 != ''")).scalar()
|
||||
pg.close()
|
||||
print(f'\n3. APDB 통계:')
|
||||
print(f' - 전체 APC: {total_apc:,}개')
|
||||
print(f' - 이미지 있음: {with_image:,}개 ({with_image/total_apc*100:.1f}%)')
|
||||
|
||||
# 4. CD_ITEM_UNIT_MEMBER 구조 확인
|
||||
print(f'\n4. 현재 APC 매핑 상태:')
|
||||
for r in has_apc[:5]:
|
||||
print(f' ✅ {r.GoodsName[:25]:<25} → {r.APC_CODE}')
|
||||
|
||||
session.close()
|
||||
print('\n=== 측정 완료 ===')
|
||||
89
backend/scripts/prepare_apc_insert.py
Normal file
@ -0,0 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
안텔민뽀삐 APC 추가 준비 스크립트
|
||||
- CD_ITEM_UNIT_MEMBER 구조 확인
|
||||
- 안텔민킹 레코드 참고
|
||||
- INSERT 쿼리 생성 (실행 안 함)
|
||||
"""
|
||||
import sys
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
|
||||
print('=' * 60)
|
||||
print('1. CD_ITEM_UNIT_MEMBER 테이블 구조')
|
||||
print('=' * 60)
|
||||
result = session.execute(text("""
|
||||
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, CHARACTER_MAXIMUM_LENGTH
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_NAME = 'CD_ITEM_UNIT_MEMBER'
|
||||
ORDER BY ORDINAL_POSITION
|
||||
"""))
|
||||
for r in result:
|
||||
nullable = 'NULL' if r.IS_NULLABLE == 'YES' else 'NOT NULL'
|
||||
length = f'({r.CHARACTER_MAXIMUM_LENGTH})' if r.CHARACTER_MAXIMUM_LENGTH else ''
|
||||
print(f' {r.COLUMN_NAME}: {r.DATA_TYPE}{length} {nullable}')
|
||||
|
||||
print('\n' + '=' * 60)
|
||||
print('2. 안텔민킹 APC 레코드 (참고용)')
|
||||
print('=' * 60)
|
||||
result = session.execute(text("""
|
||||
SELECT * FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = 'LB000003157'
|
||||
AND CD_CD_BARCODE LIKE '023%'
|
||||
"""))
|
||||
row = result.fetchone()
|
||||
if row:
|
||||
cols = result.keys()
|
||||
for col in cols:
|
||||
val = getattr(row, col)
|
||||
print(f' {col}: {val}')
|
||||
|
||||
print('\n' + '=' * 60)
|
||||
print('3. 안텔민뽀삐 현재 레코드')
|
||||
print('=' * 60)
|
||||
result2 = session.execute(text("""
|
||||
SELECT * FROM CD_ITEM_UNIT_MEMBER
|
||||
WHERE DRUGCODE = 'LB000003158'
|
||||
ORDER BY SN DESC
|
||||
"""))
|
||||
rows = list(result2)
|
||||
print(f' 총 {len(rows)}개 레코드')
|
||||
for row in rows[:3]:
|
||||
print(f'\n --- SN: {row.SN} ---')
|
||||
cols = result2.keys()
|
||||
for col in cols:
|
||||
val = getattr(row, col)
|
||||
print(f' {col}: {val}')
|
||||
|
||||
print('\n' + '=' * 60)
|
||||
print('4. 다음 SN 값 확인')
|
||||
print('=' * 60)
|
||||
result3 = session.execute(text("SELECT MAX(SN) as max_sn FROM CD_ITEM_UNIT_MEMBER"))
|
||||
max_sn = result3.fetchone().max_sn
|
||||
print(f' 현재 MAX(SN): {max_sn}')
|
||||
print(f' 다음 SN: {max_sn + 1}')
|
||||
|
||||
session.close()
|
||||
|
||||
print('\n' + '=' * 60)
|
||||
print('5. PostgreSQL에서 안텔민뽀삐 APC 확인')
|
||||
print('=' * 60)
|
||||
from sqlalchemy import create_engine
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
|
||||
result4 = pg.execute(text("""
|
||||
SELECT apc, product_name
|
||||
FROM apc
|
||||
WHERE product_name ILIKE '%안텔민%뽀삐%' OR product_name ILIKE '%안텔민%5kg%이하%'
|
||||
ORDER BY apc
|
||||
"""))
|
||||
for r in result4:
|
||||
print(f' APC: {r.apc}')
|
||||
print(f' 제품명: {r.product_name}')
|
||||
print()
|
||||
pg.close()
|
||||
168
backend/scripts/query_aniparm.py
Normal file
@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
애니팜 PostgreSQL 조회 스크립트
|
||||
Usage:
|
||||
python scripts/query_aniparm.py schema # 테이블 구조 확인
|
||||
python scripts/query_aniparm.py search <제품명> # 제품 검색
|
||||
python scripts/query_aniparm.py barcode <바코드> # 바코드로 검색
|
||||
python scripts/query_aniparm.py sample # 샘플 데이터
|
||||
python scripts/query_aniparm.py stats # 통계
|
||||
"""
|
||||
import sys
|
||||
import io
|
||||
import json
|
||||
|
||||
# ═══════════════════════════════════════════════════════════
|
||||
# 인코딩 설정 (Windows CP949 문제 방지)
|
||||
# ═══════════════════════════════════════════════════════════
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
# PostgreSQL 연결
|
||||
DATABASE_URI = 'postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master'
|
||||
|
||||
def get_connection():
|
||||
engine = create_engine(DATABASE_URI)
|
||||
return engine.connect()
|
||||
|
||||
def cmd_schema():
|
||||
"""apc 테이블 구조 확인"""
|
||||
conn = get_connection()
|
||||
result = conn.execute(text("""
|
||||
SELECT column_name, data_type, character_maximum_length
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'apc'
|
||||
ORDER BY ordinal_position
|
||||
"""))
|
||||
|
||||
print('=== apc 테이블 컬럼 ===')
|
||||
for row in result:
|
||||
length = f'({row.character_maximum_length})' if row.character_maximum_length else ''
|
||||
print(f' {row.column_name}: {row.data_type}{length}')
|
||||
|
||||
conn.close()
|
||||
|
||||
def cmd_search(keyword):
|
||||
"""제품명으로 검색"""
|
||||
conn = get_connection()
|
||||
result = conn.execute(text("""
|
||||
SELECT idx, apc, product_name, company_name,
|
||||
image_url1, godoimage_url_f, for_pets
|
||||
FROM apc
|
||||
WHERE product_name ILIKE :keyword
|
||||
LIMIT 20
|
||||
"""), {'keyword': f'%{keyword}%'})
|
||||
|
||||
print(f'=== "{keyword}" 검색 결과 ===')
|
||||
count = 0
|
||||
for row in result:
|
||||
count += 1
|
||||
print(f'\n[{count}] {row.product_name}')
|
||||
print(f' APC: {row.apc}')
|
||||
print(f' 제조사: {row.company_name}')
|
||||
print(f' 동물용: {row.for_pets}')
|
||||
if row.image_url1:
|
||||
print(f' 이미지1: {row.image_url1[:50]}...')
|
||||
if row.godoimage_url_f:
|
||||
print(f' 고도몰F: {row.godoimage_url_f[:50]}...')
|
||||
|
||||
if count == 0:
|
||||
print('(결과 없음)')
|
||||
|
||||
conn.close()
|
||||
|
||||
def cmd_barcode(barcode):
|
||||
"""바코드로 검색 - 바코드 컬럼이 있는지 먼저 확인"""
|
||||
conn = get_connection()
|
||||
|
||||
# 바코드 관련 컬럼 찾기
|
||||
result = conn.execute(text("""
|
||||
SELECT column_name FROM information_schema.columns
|
||||
WHERE table_name = 'apc'
|
||||
AND column_name ILIKE '%barcode%'
|
||||
"""))
|
||||
|
||||
barcode_cols = [row.column_name for row in result]
|
||||
|
||||
if not barcode_cols:
|
||||
print('apc 테이블에 barcode 관련 컬럼이 없습니다.')
|
||||
print('다른 컬럼으로 검색해야 합니다.')
|
||||
else:
|
||||
print(f'바코드 컬럼 발견: {barcode_cols}')
|
||||
# TODO: 바코드로 검색 구현
|
||||
|
||||
conn.close()
|
||||
|
||||
def cmd_sample():
|
||||
"""샘플 데이터 (동물용 제품)"""
|
||||
conn = get_connection()
|
||||
result = conn.execute(text("""
|
||||
SELECT idx, apc, product_name, company_name,
|
||||
image_url1, godoimage_url_f, for_pets
|
||||
FROM apc
|
||||
WHERE for_pets = true
|
||||
LIMIT 10
|
||||
"""))
|
||||
|
||||
print('=== 동물용 제품 샘플 ===')
|
||||
count = 0
|
||||
for row in result:
|
||||
count += 1
|
||||
print(f'\n[{count}] {row.product_name}')
|
||||
print(f' APC: {row.apc}')
|
||||
print(f' 제조사: {row.company_name}')
|
||||
img = row.image_url1 or row.godoimage_url_f or '(없음)'
|
||||
if len(img) > 50:
|
||||
img = img[:50] + '...'
|
||||
print(f' 이미지: {img}')
|
||||
|
||||
if count == 0:
|
||||
print('(동물용 제품 없음 - for_pets 필터 확인 필요)')
|
||||
|
||||
conn.close()
|
||||
|
||||
def cmd_stats():
|
||||
"""통계"""
|
||||
conn = get_connection()
|
||||
|
||||
result = conn.execute(text("""
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
SUM(CASE WHEN for_pets = true THEN 1 ELSE 0 END) as pet_count,
|
||||
SUM(CASE WHEN image_url1 IS NOT NULL AND image_url1 != '' THEN 1 ELSE 0 END) as has_img1,
|
||||
SUM(CASE WHEN godoimage_url_f IS NOT NULL AND godoimage_url_f != '' THEN 1 ELSE 0 END) as has_godo_f
|
||||
FROM apc
|
||||
"""))
|
||||
|
||||
row = result.fetchone()
|
||||
print('=== apc 테이블 통계 ===')
|
||||
print(f'전체 제품: {row.total:,}개')
|
||||
print(f'동물용(for_pets=true): {row.pet_count:,}개')
|
||||
print(f'image_url1 있음: {row.has_img1:,}개')
|
||||
print(f'godoimage_url_f 있음: {row.has_godo_f:,}개')
|
||||
|
||||
conn.close()
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
return
|
||||
|
||||
cmd = sys.argv[1]
|
||||
|
||||
if cmd == 'schema':
|
||||
cmd_schema()
|
||||
elif cmd == 'search' and len(sys.argv) > 2:
|
||||
cmd_search(sys.argv[2])
|
||||
elif cmd == 'barcode' and len(sys.argv) > 2:
|
||||
cmd_barcode(sys.argv[2])
|
||||
elif cmd == 'sample':
|
||||
cmd_sample()
|
||||
elif cmd == 'stats':
|
||||
cmd_stats()
|
||||
else:
|
||||
print(__doc__)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
27
backend/scripts/show_llm_pharm.py
Normal file
@ -0,0 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io, json
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
|
||||
|
||||
# 안텔민킹 llm_pharm 전체 확인
|
||||
result = pg.execute(text("""
|
||||
SELECT product_name, llm_pharm FROM apc WHERE apc = '0230237810109'
|
||||
"""))
|
||||
row = result.fetchone()
|
||||
|
||||
print('=== 안텔민킹 llm_pharm 전체 키 ===\n')
|
||||
data = row.llm_pharm
|
||||
for k in sorted(data.keys()):
|
||||
val = str(data[k])
|
||||
if len(val) > 60:
|
||||
val = val[:60] + '...'
|
||||
print(f' {k}: {val}')
|
||||
|
||||
# 동물약 전체 개수
|
||||
print('\n=== PostgreSQL 동물약 전체 개수 ===')
|
||||
result2 = pg.execute(text("SELECT COUNT(*) FROM apc"))
|
||||
print(f' 전체: {result2.fetchone()[0]}개')
|
||||
|
||||
pg.close()
|
||||
@ -26,6 +26,11 @@ ANIMAL_KEYWORDS = [
|
||||
'펫팜', '동물약품', '애니팜'
|
||||
]
|
||||
|
||||
# 동물약 공급처 (SplName이 이 값이면 전부 동물약)
|
||||
ANIMAL_SUPPLIERS = [
|
||||
'펫팜'
|
||||
]
|
||||
|
||||
# 제외 키워드 (사람용 약)
|
||||
EXCLUDE_KEYWORDS = [
|
||||
'헤리펫사', '토피라펫', '메타트레이스', '페리돈', '세파라캅'
|
||||
@ -58,24 +63,38 @@ def init_sqlite_db():
|
||||
print(f"✅ SQLite DB 준비: {DB_PATH}")
|
||||
|
||||
def search_animal_drugs():
|
||||
"""MSSQL에서 동물약 키워드 검색"""
|
||||
"""MSSQL에서 동물약 검색 (키워드 + 공급처)"""
|
||||
print("🔍 CD_GOODS에서 동물약 검색 중...")
|
||||
|
||||
|
||||
session = db_manager.get_session('PM_DRUG')
|
||||
|
||||
# 키워드 조건 생성
|
||||
conditions = ' OR '.join([f"GoodsName LIKE '%{kw}%'" for kw in ANIMAL_KEYWORDS])
|
||||
|
||||
|
||||
# 키워드 조건
|
||||
keyword_conds = ' OR '.join([f"GoodsName LIKE '%{kw}%'" for kw in ANIMAL_KEYWORDS])
|
||||
|
||||
# 공급처 조건
|
||||
supplier_conds = ' OR '.join([f"SplName = '{sp}'" for sp in ANIMAL_SUPPLIERS])
|
||||
|
||||
query = text(f"""
|
||||
SELECT DrugCode, GoodsName, BARCODE, POS_BOON
|
||||
SELECT DrugCode, GoodsName, BARCODE, POS_BOON, SplName
|
||||
FROM CD_GOODS
|
||||
WHERE ({conditions})
|
||||
WHERE (({keyword_conds}) OR ({supplier_conds}))
|
||||
AND GoodsSelCode = 'B'
|
||||
""")
|
||||
|
||||
|
||||
result = session.execute(query)
|
||||
drugs = result.fetchall()
|
||||
print(f"✅ 발견: {len(drugs)}개")
|
||||
|
||||
# 키워드 vs 공급처 통계
|
||||
by_keyword = [d for d in drugs if any(kw in (d.GoodsName or '') for kw in ANIMAL_KEYWORDS)]
|
||||
by_supplier = [d for d in drugs if d.SplName in ANIMAL_SUPPLIERS]
|
||||
supplier_only = [d for d in by_supplier if not any(kw in (d.GoodsName or '') for kw in ANIMAL_KEYWORDS)]
|
||||
|
||||
print(f"✅ 발견: {len(drugs)}개 (키워드: {len(by_keyword)}, 공급처 추가: {len(supplier_only)})")
|
||||
if supplier_only:
|
||||
print(" 📦 공급처 기반 신규:")
|
||||
for d in supplier_only:
|
||||
print(f" {d.DrugCode}: {d.GoodsName} ({d.SplName})")
|
||||
|
||||
return drugs
|
||||
|
||||
def tag_to_sqlite(drugs):
|
||||
@ -93,20 +112,27 @@ def tag_to_sqlite(drugs):
|
||||
drug_code = drug[0]
|
||||
drug_name = drug[1] or ''
|
||||
barcode = drug[2]
|
||||
|
||||
spl_name = drug[4] if len(drug) > 4 else ''
|
||||
|
||||
# 제외 키워드 체크
|
||||
if any(ex in drug_name for ex in EXCLUDE_KEYWORDS):
|
||||
excluded += 1
|
||||
print(f" ⛔ 제외: {drug_code} - {drug_name}")
|
||||
continue
|
||||
|
||||
|
||||
# 매칭 소스 구분
|
||||
by_kw = any(kw in drug_name for kw in ANIMAL_KEYWORDS)
|
||||
by_sp = spl_name in ANIMAL_SUPPLIERS
|
||||
source = 'keyword' if by_kw else 'supplier'
|
||||
note = '키워드 자동 태깅' if by_kw else f'공급처({spl_name}) 자동 태깅'
|
||||
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO drug_tags (drug_code, drug_name, barcode, tag_type, tag_value, note)
|
||||
VALUES (?, ?, ?, 'animal_drug', 'all', '키워드 자동 태깅')
|
||||
''', (drug_code, drug_name, barcode))
|
||||
INSERT INTO drug_tags (drug_code, drug_name, barcode, tag_type, tag_value, note, source)
|
||||
VALUES (?, ?, ?, 'animal_drug', 'all', ?, ?)
|
||||
''', (drug_code, drug_name, barcode, note, source))
|
||||
added += 1
|
||||
print(f" ✅ {drug_code}: {drug_name}")
|
||||
print(f" ✅ {drug_code}: {drug_name} [{source}]")
|
||||
except sqlite3.IntegrityError:
|
||||
skipped += 1
|
||||
|
||||
|
||||
16
backend/scripts/test_gestage_api.py
Normal file
@ -0,0 +1,16 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from app import _get_animal_drugs
|
||||
|
||||
drugs = _get_animal_drugs()
|
||||
gestage = [d for d in drugs if '제스타제' in d['name']]
|
||||
|
||||
print('=== 제스타제 API 결과 ===\n')
|
||||
for d in gestage:
|
||||
print(f"name: {d['name']}")
|
||||
print(f"barcode: {d['barcode']}")
|
||||
print(f"apc: {d['apc']}")
|
||||
print(f"image_url: {d['image_url']}")
|
||||
23
backend/scripts/test_pets_migration.py
Normal file
@ -0,0 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""pets 테이블 마이그레이션 테스트"""
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import db_manager
|
||||
|
||||
# SQLite 연결 (마이그레이션 자동 실행)
|
||||
conn = db_manager.get_sqlite_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# pets 테이블 확인
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='pets'")
|
||||
if cursor.fetchone():
|
||||
print('✅ pets 테이블 생성 완료')
|
||||
cursor.execute('PRAGMA table_info(pets)')
|
||||
columns = cursor.fetchall()
|
||||
print('\n컬럼 목록:')
|
||||
for col in columns:
|
||||
print(f' - {col[1]} ({col[2]})')
|
||||
else:
|
||||
print('❌ pets 테이블 없음')
|
||||
43
backend/scripts/update_gesidin_category.py
Normal file
@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')
|
||||
|
||||
from db.dbsetup import get_db_session
|
||||
from sqlalchemy import text
|
||||
|
||||
session = get_db_session('PM_DRUG')
|
||||
|
||||
print('1. 현재 상태 확인...')
|
||||
result = session.execute(text("""
|
||||
SELECT DrugCode, GoodsName, POS_BOON
|
||||
FROM CD_GOODS
|
||||
WHERE DrugCode = 'LB000003140'
|
||||
"""))
|
||||
row = result.fetchone()
|
||||
print(f' {row.GoodsName}: POS_BOON = {row.POS_BOON}')
|
||||
|
||||
print('\n2. POS_BOON을 동물약(010103)으로 업데이트...')
|
||||
try:
|
||||
session.execute(text("""
|
||||
UPDATE CD_GOODS
|
||||
SET POS_BOON = '010103'
|
||||
WHERE DrugCode = 'LB000003140'
|
||||
"""))
|
||||
session.commit()
|
||||
print(' ✅ 성공!')
|
||||
|
||||
# 확인
|
||||
result2 = session.execute(text("""
|
||||
SELECT DrugCode, GoodsName, POS_BOON
|
||||
FROM CD_GOODS
|
||||
WHERE DrugCode = 'LB000003140'
|
||||
"""))
|
||||
row2 = result2.fetchone()
|
||||
print(f' {row2.GoodsName}: POS_BOON = {row2.POS_BOON}')
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f' ❌ 실패: {e}')
|
||||
|
||||
session.close()
|
||||
@ -98,6 +98,89 @@ class KakaoAPIClient:
|
||||
'error_description': f'Invalid JSON response: {e}'
|
||||
}
|
||||
|
||||
def refresh_access_token(self, refresh_token: str) -> Tuple[bool, Dict[str, Any]]:
|
||||
"""Refresh Token으로 Access Token 갱신"""
|
||||
url = f"{self.auth_base_url}/oauth/token"
|
||||
|
||||
data = {
|
||||
'grant_type': 'refresh_token',
|
||||
'client_id': self.client_id,
|
||||
'refresh_token': refresh_token,
|
||||
}
|
||||
if self.client_secret:
|
||||
data['client_secret'] = self.client_secret
|
||||
|
||||
try:
|
||||
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
||||
response = self.session.post(url, data=data, headers=headers)
|
||||
|
||||
logger.info(f"카카오 토큰 갱신 응답 상태: {response.status_code}")
|
||||
response.raise_for_status()
|
||||
|
||||
token_data = response.json()
|
||||
if 'expires_in' in token_data:
|
||||
expires_at = datetime.now() + timedelta(seconds=token_data['expires_in'])
|
||||
token_data['expires_at'] = expires_at.isoformat()
|
||||
|
||||
return True, token_data
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"카카오 토큰 갱신 실패: {e}")
|
||||
error_details = {
|
||||
'error': 'token_refresh_failed',
|
||||
'error_description': f'Failed to refresh access token: {e}'
|
||||
}
|
||||
try:
|
||||
if hasattr(e, 'response') and e.response is not None:
|
||||
kakao_error = e.response.json()
|
||||
logger.error(f"카카오 API 오류: {kakao_error}")
|
||||
error_details.update(kakao_error)
|
||||
except Exception:
|
||||
pass
|
||||
return False, error_details
|
||||
|
||||
def get_user_info_with_refresh(
|
||||
self,
|
||||
access_token: str,
|
||||
refresh_token: str,
|
||||
token_expires_at: str = None
|
||||
) -> Tuple[bool, Dict[str, Any], Dict[str, Any]]:
|
||||
"""저장된 토큰으로 사용자 정보 조회 (만료 시 자동 갱신)
|
||||
|
||||
Returns:
|
||||
(성공여부, 사용자정보/에러, 갱신된 토큰 데이터 또는 빈 dict)
|
||||
"""
|
||||
new_token_data = {}
|
||||
|
||||
# 만료 확인: 5분 이내면 미리 갱신
|
||||
if token_expires_at:
|
||||
try:
|
||||
expires = datetime.fromisoformat(token_expires_at)
|
||||
if datetime.now() >= expires - timedelta(minutes=5):
|
||||
logger.info("Access token 만료 임박, 갱신 시도")
|
||||
success, refreshed = self.refresh_access_token(refresh_token)
|
||||
if success:
|
||||
access_token = refreshed['access_token']
|
||||
new_token_data = refreshed
|
||||
else:
|
||||
return False, refreshed, {}
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"token_expires_at 파싱 실패, 기존 토큰으로 시도: {e}")
|
||||
|
||||
# 사용자 정보 조회
|
||||
success, user_info = self.get_user_info(access_token)
|
||||
|
||||
if not success and refresh_token:
|
||||
# 실패 시 갱신 후 재시도
|
||||
logger.info("사용자 정보 조회 실패, 토큰 갱신 후 재시도")
|
||||
refresh_ok, refreshed = self.refresh_access_token(refresh_token)
|
||||
if refresh_ok:
|
||||
access_token = refreshed['access_token']
|
||||
new_token_data = refreshed
|
||||
success, user_info = self.get_user_info(access_token)
|
||||
|
||||
return success, user_info, new_token_data
|
||||
|
||||
def get_user_info(self, access_token: str) -> Tuple[bool, Dict[str, Any]]:
|
||||
"""Access Token으로 사용자 정보 조회"""
|
||||
url = f"{self.api_base_url}/v2/user/me"
|
||||
|
||||
@ -87,7 +87,16 @@ def _send_alimtalk(template_code, recipient_no, template_params):
|
||||
logger.info(f"알림톡 발송 성공: {template_code} → {recipient_no}")
|
||||
return (True, "발송 성공")
|
||||
else:
|
||||
error_msg = result.get('header', {}).get('resultMessage', str(result))
|
||||
# 상세 에러 추출: sendResults[0].resultMessage 우선, 없으면 header.resultMessage
|
||||
header_msg = result.get('header', {}).get('resultMessage', '')
|
||||
send_results = result.get('message', {}).get('sendResults', [])
|
||||
detail_msg = send_results[0].get('resultMessage', '') if send_results else ''
|
||||
|
||||
# 상세 에러가 있으면 그걸 사용, 없으면 header 에러
|
||||
error_msg = detail_msg if detail_msg and detail_msg != 'SUCCESS' else header_msg
|
||||
if not error_msg:
|
||||
error_msg = str(result)
|
||||
|
||||
logger.warning(f"알림톡 발송 실패: {template_code} → {recipient_no}: {error_msg}")
|
||||
return (False, error_msg)
|
||||
|
||||
@ -100,15 +109,25 @@ def _send_alimtalk(template_code, recipient_no, template_params):
|
||||
|
||||
|
||||
def build_item_summary(items):
|
||||
"""구매 품목 요약 문자열 생성 (예: '타이레놀 외 3건')"""
|
||||
"""구매 품목 요약 문자열 생성 (예: '타이레놀 외 3건')
|
||||
|
||||
Note: 카카오 알림톡 템플릿 변수는 14자 제한
|
||||
(에러: "Blacklist can't use more than 14 characters in template value.")
|
||||
특수문자(%, 괄호 등)는 문제없이 발송 가능!
|
||||
"""
|
||||
if not items:
|
||||
return "약국 구매"
|
||||
first = items[0]['name']
|
||||
if len(first) > 20:
|
||||
first = first[:18] + '..'
|
||||
first = first.strip()
|
||||
|
||||
if len(items) == 1:
|
||||
return first
|
||||
return f"{first} 외 {len(items) - 1}건"
|
||||
# 단일 품목: 14자 제한 (그냥 자름)
|
||||
return first[:14]
|
||||
|
||||
# 복수 품목: "외 N건" 붙으므로 전체 14자 맞춤
|
||||
suffix = f" 외 {len(items) - 1}건"
|
||||
max_first = 14 - len(suffix)
|
||||
return f"{first[:max_first]}{suffix}"
|
||||
|
||||
|
||||
def send_mileage_claim_alimtalk(phone, name, points, balance, items=None,
|
||||
@ -146,24 +165,7 @@ def send_mileage_claim_alimtalk(phone, name, points, balance, items=None,
|
||||
|
||||
success, msg = _send_alimtalk(template_code, phone, params)
|
||||
|
||||
if not success:
|
||||
# V3 실패 로그
|
||||
_log_to_db(template_code, phone, False, msg,
|
||||
template_params=params, user_id=user_id,
|
||||
trigger_source=trigger_source, transaction_id=transaction_id)
|
||||
|
||||
# V2 폴백
|
||||
template_code = 'MILEAGE_CLAIM_V2'
|
||||
params = {
|
||||
'고객명': name,
|
||||
'적립포인트': f'{points:,}',
|
||||
'총잔액': f'{balance:,}',
|
||||
'적립일시': now_kst,
|
||||
'전화번호': phone
|
||||
}
|
||||
success, msg = _send_alimtalk(template_code, phone, params)
|
||||
|
||||
# 최종 결과 로그
|
||||
# 결과 로그 (V3만 사용, V2 폴백 제거 - V2 반려 상태)
|
||||
_log_to_db(template_code, phone, success, msg,
|
||||
template_params=params, user_id=user_id,
|
||||
trigger_source=trigger_source, transaction_id=transaction_id)
|
||||
|
||||
706
backend/sooin_api.py
Normal file
@ -0,0 +1,706 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
수인약품 도매상 API - Flask Blueprint
|
||||
|
||||
핵심 로직은 wholesale 패키지에서 가져옴
|
||||
이 파일은 Flask 웹 API 연동만 담당
|
||||
"""
|
||||
|
||||
import time
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, jsonify, request as flask_request
|
||||
|
||||
# wholesale 패키지 경로 설정
|
||||
import wholesale_path
|
||||
|
||||
# wholesale 패키지에서 핵심 클래스 가져오기
|
||||
from wholesale import SooinSession
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Blueprint 생성
|
||||
sooin_bp = Blueprint('sooin', __name__, url_prefix='/api/sooin')
|
||||
|
||||
|
||||
# ========== 세션 관리 ==========
|
||||
|
||||
_sooin_session = None
|
||||
|
||||
def get_sooin_session():
|
||||
global _sooin_session
|
||||
if _sooin_session is None:
|
||||
_sooin_session = SooinSession()
|
||||
return _sooin_session
|
||||
|
||||
|
||||
def search_sooin_stock(keyword: str, search_type: str = 'kd_code'):
|
||||
"""수인약품 재고 검색 (동기, 빠름)"""
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.search_products(keyword)
|
||||
|
||||
if result.get('success'):
|
||||
return {
|
||||
'success': True,
|
||||
'keyword': keyword,
|
||||
'search_type': search_type,
|
||||
'count': result['total'],
|
||||
'items': result['items']
|
||||
}
|
||||
else:
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 검색 오류: {e}")
|
||||
return {'success': False, 'error': 'SEARCH_ERROR', 'message': str(e)}
|
||||
|
||||
|
||||
# ========== Flask API Routes ==========
|
||||
|
||||
@sooin_bp.route('/stock', methods=['GET'])
|
||||
def api_sooin_stock():
|
||||
"""
|
||||
수인약품 재고 조회 API
|
||||
|
||||
GET /api/sooin/stock?kd_code=073100220
|
||||
GET /api/sooin/stock?keyword=코자정&type=name
|
||||
"""
|
||||
kd_code = flask_request.args.get('kd_code', '').strip()
|
||||
keyword = flask_request.args.get('keyword', '').strip()
|
||||
search_type = flask_request.args.get('type', 'kd_code').strip()
|
||||
|
||||
search_term = kd_code or keyword
|
||||
if kd_code:
|
||||
search_type = 'kd_code'
|
||||
|
||||
if not search_term:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'kd_code 또는 keyword 파라미터가 필요합니다'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
result = search_sooin_stock(search_term, search_type)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 API 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'API_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/session-status', methods=['GET'])
|
||||
def api_session_status():
|
||||
"""세션 상태 확인"""
|
||||
session = get_sooin_session()
|
||||
return jsonify({
|
||||
'logged_in': session._logged_in,
|
||||
'last_login': session._last_login,
|
||||
'session_age_sec': int(time.time() - session._last_login) if session._last_login else None
|
||||
})
|
||||
|
||||
|
||||
@sooin_bp.route('/balance', methods=['GET'])
|
||||
def api_sooin_balance():
|
||||
"""
|
||||
수인약품 잔고(미수금) 조회 API
|
||||
|
||||
GET /api/sooin/balance
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"balance": 14293001, // 현재 잔고 (누계합)
|
||||
"prev_balance": 10592762, // 전일잔액
|
||||
"monthly_sales": 3700239, // 월 매출
|
||||
"yearly_sales": 34380314 // 연 누계 매출
|
||||
}
|
||||
"""
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.get_balance()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 잔고 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'BALANCE_ERROR',
|
||||
'message': str(e),
|
||||
'balance': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/monthly-sales', methods=['GET'])
|
||||
def api_sooin_monthly_sales():
|
||||
"""
|
||||
수인약품 월간 매출 조회 API
|
||||
|
||||
GET /api/sooin/monthly-sales?year=2026&month=3
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"total_amount": 3700239, // 월간 매출 합계
|
||||
"total_paid": 0, // 월간 입금 합계
|
||||
"ending_balance": 14293001, // 월말 잔액
|
||||
"opening_balance": 10592762, // 전일(기초) 잔액
|
||||
"from_date": "2026-03-01",
|
||||
"to_date": "2026-03-31"
|
||||
}
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
year = flask_request.args.get('year', type=int)
|
||||
month = flask_request.args.get('month', type=int)
|
||||
|
||||
# 기본값: 현재 월
|
||||
if not year or not month:
|
||||
now = datetime.now()
|
||||
year = year or now.year
|
||||
month = month or now.month
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
if hasattr(session, 'get_monthly_sales'):
|
||||
result = session.get_monthly_sales(year, month)
|
||||
return jsonify(result)
|
||||
else:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'NOT_IMPLEMENTED',
|
||||
'message': '수인약품 월간 매출 조회 미구현'
|
||||
}), 501
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 월간 매출 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MONTHLY_SALES_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/cart', methods=['GET'])
|
||||
def api_sooin_cart():
|
||||
"""장바구니 조회 API"""
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.get_cart()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e), 'items': []}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/cart/clear', methods=['POST'])
|
||||
def api_sooin_cart_clear():
|
||||
"""장바구니 비우기 API"""
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.clear_cart()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/cart/cancel', methods=['POST'])
|
||||
def api_sooin_cart_cancel():
|
||||
"""
|
||||
장바구니 항목 취소 API
|
||||
|
||||
POST /api/sooin/cart/cancel
|
||||
{ "row_index": 0 }
|
||||
또는
|
||||
{ "internal_code": "32495" }
|
||||
"""
|
||||
data = flask_request.get_json() or {}
|
||||
row_index = data.get('row_index')
|
||||
internal_code = data.get('internal_code')
|
||||
|
||||
if row_index is None and not internal_code:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'row_index 또는 internal_code가 필요합니다'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.cancel_item(row_index=row_index, product_code=internal_code)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/cart/restore', methods=['POST'])
|
||||
def api_sooin_cart_restore():
|
||||
"""
|
||||
취소된 항목 복원 API
|
||||
|
||||
POST /api/sooin/cart/restore
|
||||
{ "row_index": 0 }
|
||||
"""
|
||||
data = flask_request.get_json() or {}
|
||||
row_index = data.get('row_index')
|
||||
internal_code = data.get('internal_code')
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.restore_item(row_index=row_index, product_code=internal_code)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/order', methods=['POST'])
|
||||
def api_sooin_order():
|
||||
"""
|
||||
수인약품 주문 API (장바구니 추가)
|
||||
|
||||
POST /api/sooin/order
|
||||
{
|
||||
"kd_code": "073100220",
|
||||
"quantity": 1,
|
||||
"specification": "30T",
|
||||
"check_stock": true
|
||||
}
|
||||
"""
|
||||
data = flask_request.get_json()
|
||||
|
||||
if not data:
|
||||
return jsonify({'success': False, 'error': 'NO_DATA'}), 400
|
||||
|
||||
kd_code = data.get('kd_code', '').strip()
|
||||
quantity = data.get('quantity', 1)
|
||||
specification = data.get('specification')
|
||||
check_stock = data.get('check_stock', True)
|
||||
|
||||
if not kd_code:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'MISSING_PARAM',
|
||||
'message': 'kd_code가 필요합니다'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.quick_order(
|
||||
kd_code=kd_code,
|
||||
quantity=quantity,
|
||||
spec=specification,
|
||||
check_stock=check_stock
|
||||
)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 주문 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'ORDER_ERROR',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/confirm', methods=['POST'])
|
||||
def api_sooin_confirm():
|
||||
"""주문 확정 API"""
|
||||
data = flask_request.get_json() or {}
|
||||
memo = data.get('memo', '')
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.submit_order(memo)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/full-order', methods=['POST'])
|
||||
def api_sooin_full_order():
|
||||
"""
|
||||
전체 주문 API (검색 → 장바구니 → 확정)
|
||||
|
||||
POST /api/sooin/full-order
|
||||
{
|
||||
"kd_code": "073100220",
|
||||
"quantity": 1,
|
||||
"specification": "30T",
|
||||
"auto_confirm": true,
|
||||
"memo": "자동주문"
|
||||
}
|
||||
"""
|
||||
data = flask_request.get_json()
|
||||
|
||||
if not data or not data.get('kd_code'):
|
||||
return jsonify({'success': False, 'error': 'kd_code required'}), 400
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
|
||||
# 장바구니에 담기
|
||||
cart_result = session.quick_order(
|
||||
kd_code=data['kd_code'],
|
||||
quantity=data.get('quantity', 1),
|
||||
spec=data.get('specification'),
|
||||
check_stock=data.get('check_stock', True)
|
||||
)
|
||||
|
||||
if not cart_result.get('success'):
|
||||
return jsonify(cart_result)
|
||||
|
||||
if not data.get('auto_confirm', True):
|
||||
return jsonify(cart_result)
|
||||
|
||||
# 주문 확정
|
||||
confirm_result = session.submit_order(data.get('memo', ''))
|
||||
|
||||
if confirm_result.get('success'):
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': f"{cart_result['product']['name']} {cart_result['quantity']}개 주문 완료",
|
||||
'product': cart_result['product'],
|
||||
'quantity': cart_result['quantity'],
|
||||
'confirmed': True
|
||||
})
|
||||
else:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': confirm_result.get('error', 'CONFIRM_FAILED'),
|
||||
'message': f"장바구니 담기 성공, 주문 확정 실패",
|
||||
'product': cart_result['product'],
|
||||
'cart_added': True
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/order-batch', methods=['POST'])
|
||||
def api_sooin_order_batch():
|
||||
"""수인약품 일괄 주문 API"""
|
||||
data = flask_request.get_json()
|
||||
|
||||
if not data or not data.get('items'):
|
||||
return jsonify({'success': False, 'error': 'NO_ITEMS'}), 400
|
||||
|
||||
items = data.get('items', [])
|
||||
check_stock = data.get('check_stock', True)
|
||||
|
||||
session = get_sooin_session()
|
||||
results = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
|
||||
for item in items:
|
||||
kd_code = item.get('kd_code', '').strip()
|
||||
quantity = item.get('quantity', 1)
|
||||
specification = item.get('specification')
|
||||
|
||||
if not kd_code:
|
||||
results.append({
|
||||
'kd_code': kd_code,
|
||||
'success': False,
|
||||
'error': 'MISSING_KD_CODE'
|
||||
})
|
||||
failed_count += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
result = session.quick_order(
|
||||
kd_code=kd_code,
|
||||
quantity=quantity,
|
||||
spec=specification,
|
||||
check_stock=check_stock
|
||||
)
|
||||
result['kd_code'] = kd_code
|
||||
result['requested_qty'] = quantity
|
||||
results.append(result)
|
||||
|
||||
if result.get('success'):
|
||||
success_count += 1
|
||||
else:
|
||||
failed_count += 1
|
||||
|
||||
except Exception as e:
|
||||
results.append({
|
||||
'kd_code': kd_code,
|
||||
'success': False,
|
||||
'error': 'EXCEPTION',
|
||||
'message': str(e)
|
||||
})
|
||||
failed_count += 1
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'total': len(items),
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'results': results
|
||||
})
|
||||
|
||||
|
||||
# ========== 주문 조회 API ==========
|
||||
|
||||
@sooin_bp.route('/orders', methods=['GET'])
|
||||
def api_sooin_orders():
|
||||
"""
|
||||
수인약품 주문 목록 조회 API
|
||||
|
||||
GET /api/sooin/orders?start_date=2026-03-01&end_date=2026-03-07
|
||||
|
||||
파라미터:
|
||||
start_date: 시작일 (YYYY-MM-DD), 기본값: 오늘
|
||||
end_date: 종료일 (YYYY-MM-DD), 기본값: 오늘
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"orders": [
|
||||
{
|
||||
"order_num": "202603095091177",
|
||||
"order_date": "2026-03-09",
|
||||
"order_time": "14:30:25",
|
||||
"total_amount": 125000,
|
||||
"item_count": 5,
|
||||
"status": "완료"
|
||||
}
|
||||
],
|
||||
"total_count": 10
|
||||
}
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
start_date = flask_request.args.get('start_date', today).strip()
|
||||
end_date = flask_request.args.get('end_date', today).strip()
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.get_order_list(start_date, end_date)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 주문 목록 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'ORDERS_ERROR',
|
||||
'message': str(e),
|
||||
'orders': [],
|
||||
'total_count': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/orders/today-summary', methods=['GET'])
|
||||
def api_sooin_today_summary():
|
||||
"""
|
||||
수인약품 오늘 주문 집계 API
|
||||
|
||||
GET /api/sooin/orders/today-summary
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"date": "2026-03-09",
|
||||
"summary": [
|
||||
{
|
||||
"kd_code": "073100220",
|
||||
"product_name": "코자정50mg",
|
||||
"total_quantity": 10,
|
||||
"total_amount": 150000,
|
||||
"order_count": 3
|
||||
}
|
||||
],
|
||||
"grand_total_amount": 500000,
|
||||
"grand_total_items": 25,
|
||||
"order_count": 5
|
||||
}
|
||||
"""
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.get_today_order_summary()
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 오늘 주문 집계 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'TODAY_SUMMARY_ERROR',
|
||||
'message': str(e),
|
||||
'summary': [],
|
||||
'grand_total_amount': 0,
|
||||
'grand_total_items': 0,
|
||||
'order_count': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/orders/<order_num>', methods=['GET'])
|
||||
def api_sooin_order_detail(order_num):
|
||||
"""
|
||||
수인약품 주문 상세 조회 API
|
||||
|
||||
GET /api/sooin/orders/202603095091177
|
||||
|
||||
Returns:
|
||||
{
|
||||
"success": true,
|
||||
"order_num": "202603095091177",
|
||||
"order_date": "2026-03-09",
|
||||
"items": [
|
||||
{
|
||||
"product_code": "32495",
|
||||
"kd_code": "073100220",
|
||||
"product_name": "코자정50mg",
|
||||
"spec": "30T",
|
||||
"quantity": 2,
|
||||
"unit_price": 15000,
|
||||
"amount": 30000
|
||||
}
|
||||
],
|
||||
"total_amount": 125000,
|
||||
"item_count": 5
|
||||
}
|
||||
"""
|
||||
if not order_num or not order_num.isdigit():
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'INVALID_ORDER_NUM',
|
||||
'message': '유효한 주문번호를 입력하세요'
|
||||
}), 400
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
result = session.get_order_detail(order_num)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 주문 상세 조회 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'ORDER_DETAIL_ERROR',
|
||||
'message': str(e),
|
||||
'order_num': order_num,
|
||||
'items': [],
|
||||
'total_amount': 0
|
||||
}), 500
|
||||
|
||||
|
||||
@sooin_bp.route('/orders/summary-by-kd', methods=['GET'])
|
||||
def api_sooin_orders_by_kd():
|
||||
"""
|
||||
수인약품 주문량 KD코드별 집계 API (병렬 처리)
|
||||
|
||||
GET /api/sooin/orders/summary-by-kd?start_date=2026-03-01&end_date=2026-03-07
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
start_date = flask_request.args.get('start_date', today).strip()
|
||||
end_date = flask_request.args.get('end_date', today).strip()
|
||||
|
||||
def parse_spec(spec: str) -> int:
|
||||
"""
|
||||
규격에서 박스당 단위 수 추출
|
||||
|
||||
정량 단위 (T, 정, 캡슐, C, PTP, 포 등): 숫자 추출
|
||||
용량 단위 (g, ml, mL, mg, L 등): 1 반환 (튜브/병 단위)
|
||||
|
||||
예시:
|
||||
- '30T' → 30 (정제 30정)
|
||||
- '100정(PTP)' → 100
|
||||
- '15g' → 1 (튜브 1개)
|
||||
- '10ml' → 1 (병 1개)
|
||||
- '500mg' → 1 (용량 표시)
|
||||
"""
|
||||
if not spec:
|
||||
return 1
|
||||
|
||||
spec_lower = spec.lower()
|
||||
|
||||
# 용량 단위 패턴: 숫자 + g/ml/mg/l (단독 또는 끝)
|
||||
# 이 경우 튜브/병 단위이므로 1 반환
|
||||
volume_pattern = r'^\d+\s*(g|ml|mg|l)(\s|$|\)|/)'
|
||||
if re.search(volume_pattern, spec_lower):
|
||||
return 1
|
||||
|
||||
# 정량 단위 패턴: 숫자 + T/정/캡슐/C/PTP/포
|
||||
qty_pattern = r'(\d+)\s*(t|정|캡슐?|c|ptp|포|tab|cap)'
|
||||
qty_match = re.search(qty_pattern, spec_lower)
|
||||
if qty_match:
|
||||
return int(qty_match.group(1))
|
||||
|
||||
# 기본: 숫자만 있으면 추출하되, 용량 단위 재확인
|
||||
# 끝에 g/ml이 있으면 1 반환
|
||||
if re.search(r'\d+(g|ml)$', spec_lower):
|
||||
return 1
|
||||
|
||||
# 그 외 숫자 추출
|
||||
match = re.search(r'(\d+)', spec)
|
||||
return int(match.group(1)) if match else 1
|
||||
|
||||
try:
|
||||
session = get_sooin_session()
|
||||
|
||||
# 주문 목록 조회
|
||||
orders_result = session.get_order_list(start_date, end_date)
|
||||
|
||||
if not orders_result.get('success'):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': orders_result.get('error', 'ORDERS_FETCH_FAILED'),
|
||||
'by_kd_code': {}
|
||||
})
|
||||
|
||||
orders = orders_result.get('orders', [])
|
||||
order_nums = [o.get('order_num') for o in orders if o.get('order_num')]
|
||||
|
||||
# 순차 처리 + 캐시 (캐시 효과 극대화)
|
||||
all_details = []
|
||||
|
||||
for order_num in order_nums:
|
||||
try:
|
||||
detail = session.get_order_detail(order_num)
|
||||
if detail.get('success'):
|
||||
all_details.append(detail)
|
||||
except Exception as e:
|
||||
logger.warning(f"주문 상세 조회 실패: {e}")
|
||||
|
||||
# KD코드별 집계
|
||||
kd_summary = {}
|
||||
|
||||
for detail in all_details:
|
||||
for item in detail.get('items', []):
|
||||
kd_code = item.get('kd_code', '')
|
||||
if not kd_code:
|
||||
continue
|
||||
|
||||
product_name = item.get('product_name', '')
|
||||
spec = item.get('spec', '')
|
||||
quantity = item.get('quantity', 0)
|
||||
per_unit = parse_spec(spec)
|
||||
total_units = quantity * per_unit
|
||||
|
||||
if kd_code not in kd_summary:
|
||||
kd_summary[kd_code] = {
|
||||
'product_name': product_name,
|
||||
'spec': spec,
|
||||
'boxes': 0,
|
||||
'units': 0
|
||||
}
|
||||
|
||||
kd_summary[kd_code]['boxes'] += quantity
|
||||
kd_summary[kd_code]['units'] += total_units
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'order_count': len(order_nums),
|
||||
'period': {'start': start_date, 'end': end_date},
|
||||
'by_kd_code': kd_summary,
|
||||
'total_products': len(kd_summary)
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"수인약품 KD코드별 집계 오류: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'SUMMARY_ERROR',
|
||||
'message': str(e),
|
||||
'by_kd_code': {}
|
||||
}), 500
|
||||
1072
backend/static/docs/AI_ERP.html
Normal file
BIN
backend/static/img/logo_baekje.ico
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
16
backend/static/img/logo_baekje.svg
Normal file
@ -0,0 +1,16 @@
|
||||
<svg id="logo_foot" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64.36" height="32" viewBox="0 0 64.36 32">
|
||||
<defs>
|
||||
<clipPath id="clip-path">
|
||||
<rect id="Rectangle_4823" data-name="Rectangle 4823" width="64.36" height="32" fill="#999"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<g id="Group_14242" data-name="Group 14242" clip-path="url(#clip-path)">
|
||||
<path id="Path_14020" data-name="Path 14020" d="M29.966,33.717c.348,0,.524.154.524.463v2.732h1.539V34.207a.437.437,0,0,1,.5-.49.449.449,0,0,1,.511.5v5.058a.566.566,0,0,1-.169.413.5.5,0,0,1-.676.017.634.634,0,0,1-.166-.43V37.842H30.49v1.437a.566.566,0,0,1-.169.413.474.474,0,0,1-.355.141.464.464,0,0,1-.335-.124.631.631,0,0,1-.162-.43v-5.1q0-.463.5-.463m13.23,0a.465.465,0,0,1,.345.114.4.4,0,0,1,.169.349V44.189a.476.476,0,0,1-.149.369.511.511,0,0,1-.375.161.484.484,0,0,1-.361-.141.532.532,0,0,1-.149-.389V39.1H41.088a.477.477,0,0,1-.375-.144.412.412,0,0,1-.149-.322.419.419,0,0,1,.146-.329.492.492,0,0,1,.365-.138h1.6V34.207a.434.434,0,0,1,.149-.362.533.533,0,0,1,.371-.128m2.384,0a.5.5,0,0,1,.342.128.4.4,0,0,1,.169.349v10a.467.467,0,0,1-.153.369.481.481,0,0,1-.358.161.469.469,0,0,1-.348-.141.535.535,0,0,1-.153-.389V34.207a.476.476,0,0,1,.159-.369.5.5,0,0,1,.342-.121m-21.463.235a.5.5,0,0,1,.348.124.527.527,0,0,1,.176.4V35.64h2.484v-1.2a.446.446,0,0,1,.169-.376.475.475,0,0,1,.332-.114.53.53,0,0,1,.355.128.416.416,0,0,1,.169.362v4.152a.975.975,0,0,1-.421.806,1.489,1.489,0,0,1-.942.289H24.83a1.219,1.219,0,0,1-.849-.279,1,1,0,0,1-.361-.816v-4.1a.545.545,0,0,1,.149-.4.48.48,0,0,1,.348-.141m13.041.158h4.214c.3,0,.444.131.444.4-.013.346-.159.52-.444.52H39.765v2.115a9.559,9.559,0,0,0,.623,3.581,7.858,7.858,0,0,0,1.641,2.2.452.452,0,0,1,.179.393.5.5,0,0,1-.172.332.616.616,0,0,1-.351.161.534.534,0,0,1-.4-.151,7.155,7.155,0,0,1-1.316-1.792,5.441,5.441,0,0,1-.713-2.256,5.5,5.5,0,0,1-.726,2.259A6.6,6.6,0,0,1,37.1,43.686a.658.658,0,0,1-.4.138.477.477,0,0,1-.315-.158.47.47,0,0,1-.119-.356.572.572,0,0,1,.225-.386,6.677,6.677,0,0,0,1.476-1.99,9.345,9.345,0,0,0,.773-3.779V35.026H37.145c-.325,0-.481-.158-.471-.47s.159-.446.484-.446M24.641,36.57v1.906a.324.324,0,0,0,.073.248.456.456,0,0,0,.305.074h1.628A.592.592,0,0,0,27,38.718a.286.286,0,0,0,.126-.242V36.57Zm-.2,4.323h7.255a1.425,1.425,0,0,1,.965.316,1.112,1.112,0,0,1,.381.869V44.2a.517.517,0,0,1-.176.393.477.477,0,0,1-.335.124.489.489,0,0,1-.342-.121.54.54,0,0,1-.159-.4V42.118a.305.305,0,0,0-.06-.218.494.494,0,0,0-.3-.077H24.439q-.507,0-.507-.463c0-.312.169-.467.507-.467" transform="translate(-15.788 -22.399)" fill="#999"/>
|
||||
<path id="Path_14021" data-name="Path 14021" d="M45.059,44.463a.73.73,0,0,1-.531-.217.8.8,0,0,1-.228-.575V33.689a.735.735,0,0,1,.244-.563.786.786,0,0,1,1.026,0,.647.647,0,0,1,.258.546v10a.731.731,0,0,1-.241.567.723.723,0,0,1-.528.225m0-11a.246.246,0,0,0-.173.058.211.211,0,0,0-.069.171v9.982a.273.273,0,0,0,.077.2.215.215,0,0,0,.165.064.224.224,0,0,0,.172-.082.218.218,0,0,0,.08-.187v-10a.138.138,0,0,0-.06-.135.268.268,0,0,0-.192-.08m-2.394,11a.737.737,0,0,1-.544-.217.8.8,0,0,1-.225-.575v-.642a.8.8,0,0,1-.208.3.876.876,0,0,1-.5.227.8.8,0,0,1-.6-.216,7.454,7.454,0,0,1-1.371-1.862,6.958,6.958,0,0,1-.489-1.107,6.8,6.8,0,0,1-.5,1.113,6.894,6.894,0,0,1-1.484,1.887.925.925,0,0,1-.566.2.743.743,0,0,1-.5-.242.728.728,0,0,1-.188-.546.835.835,0,0,1,.318-.575,6.445,6.445,0,0,0,1.41-1.906,9.118,9.118,0,0,0,.745-3.662V34.77H36.624a.732.732,0,0,1-.552-.2.715.715,0,0,1-.178-.538.665.665,0,0,1,.743-.7h4.214a.626.626,0,0,1,.7.658c-.027.707-.5.782-.7.782H39.5v1.853a9.335,9.335,0,0,0,.6,3.483,7.625,7.625,0,0,0,1.574,2.106.731.731,0,0,1,.215.288V38.844h-1.33A.722.722,0,0,1,40,38.613a.649.649,0,0,1-.215-.5.68.68,0,0,1,.236-.527.735.735,0,0,1,.534-.2H41.9v-3.7a.681.681,0,0,1,.251-.57.765.765,0,0,1,.519-.182.724.724,0,0,1,.52.175.65.65,0,0,1,.262.55V43.671a.738.738,0,0,1-.235.564.758.758,0,0,1-.547.228m-2.112-6.552a.229.229,0,0,0-.182.061.172.172,0,0,0-.07.144.149.149,0,0,0,.06.125.263.263,0,0,0,.205.08h1.588a.26.26,0,0,1,.259.262v5.088a.267.267,0,0,0,.074.2.226.226,0,0,0,.178.064.257.257,0,0,0,.192-.085.218.218,0,0,0,.074-.184V33.662a.141.141,0,0,0-.059-.135.23.23,0,0,0-.176-.067.363.363,0,0,0-.218.061.2.2,0,0,0-.063.167V37.65a.26.26,0,0,1-.259.262Zm-3.916-4.058c-.225,0-.225.074-.225.185a.251.251,0,0,0,.032.165.279.279,0,0,0,.18.043h1.595a.26.26,0,0,1,.259.262v2.128a9.648,9.648,0,0,1-.795,3.885A6.98,6.98,0,0,1,36.144,42.6a.324.324,0,0,0-.142.217.194.194,0,0,0,.052.153.22.22,0,0,0,.152.076.412.412,0,0,0,.219-.089,6.378,6.378,0,0,0,1.353-1.733,5.267,5.267,0,0,0,.694-2.149.26.26,0,0,1,.258-.243h0a.26.26,0,0,1,.256.246,5.206,5.206,0,0,0,.681,2.145,6.934,6.934,0,0,0,1.268,1.728.269.269,0,0,0,.209.08.357.357,0,0,0,.2-.1.226.226,0,0,0,.085-.156.188.188,0,0,0-.085-.17,8.153,8.153,0,0,1-1.706-2.282,9.855,9.855,0,0,1-.654-3.7V34.508a.26.26,0,0,1,.259-.262h1.608c.086,0,.176,0,.186-.269,0-.077,0-.124-.186-.124Zm-4.629,10.61a.744.744,0,0,1-.513-.187.808.808,0,0,1-.246-.592V41.6c0-.009,0-.017,0-.025a.477.477,0,0,0-.1-.009H23.918a.728.728,0,1,1,0-1.453h7.255a1.679,1.679,0,0,1,1.133.378,1.374,1.374,0,0,1,.472,1.068v2.125a.783.783,0,0,1-.26.586.737.737,0,0,1-.51.193m-8.091-3.826c-.237,0-.249.078-.249.2s.012.2.249.2h7.228a.738.738,0,0,1,.457.13.185.185,0,0,1,.027.024.545.545,0,0,1,.136.4v2.084a.279.279,0,0,0,.084.211.235.235,0,0,0,.159.044.223.223,0,0,0,.163-.058.252.252,0,0,0,.089-.2V41.56a.855.855,0,0,0-.294-.673,1.169,1.169,0,0,0-.794-.25Zm8.091-1.061a.72.72,0,0,1-.514-.2.914.914,0,0,1-.245-.619V37.586H30.228v1.175a.835.835,0,0,1-.245.6.729.729,0,0,1-.538.217.72.72,0,0,1-.514-.2.9.9,0,0,1-.242-.619v-5.1a.681.681,0,0,1,.756-.725.694.694,0,0,1,.783.725v2.47h1.021V33.689a.694.694,0,0,1,.759-.752.7.7,0,0,1,.769.765v5.058a.835.835,0,0,1-.245.6.713.713,0,0,1-.525.217m-.142-.56a.226.226,0,0,0,.142.037.2.2,0,0,0,.159-.065.3.3,0,0,0,.093-.228V33.7c0-.171-.035-.242-.252-.242s-.242.057-.242.228v2.705a.26.26,0,0,1-.259.262H29.969a.26.26,0,0,1-.259-.262V33.662c0-.108,0-.2-.265-.2-.227,0-.239.077-.239.2v5.1a.367.367,0,0,0,.1.255.226.226,0,0,0,.142.037.217.217,0,0,0,.172-.065.3.3,0,0,0,.093-.228V37.324a.26.26,0,0,1,.259-.262h1.539a.26.26,0,0,1,.259.262v1.437A.374.374,0,0,0,31.866,39.016Zm-5.6.416H24.309a1.473,1.473,0,0,1-1.021-.345,1.255,1.255,0,0,1-.448-1.011v-4.1a.811.811,0,0,1,.225-.584.784.784,0,0,1,1.051-.027.794.794,0,0,1,.262.6v.9h1.966v-.936a.705.705,0,0,1,.271-.584.715.715,0,0,1,.489-.168.786.786,0,0,1,.52.188.662.662,0,0,1,.262.564v4.152a1.243,1.243,0,0,1-.525,1.015,1.74,1.74,0,0,1-1.1.341M23.6,33.7a.225.225,0,0,0-.168.068.277.277,0,0,0-.07.211v4.1a.74.74,0,0,0,.267.614.975.975,0,0,0,.685.219h1.956a1.244,1.244,0,0,0,.784-.234.72.72,0,0,0,.32-.6V33.924c0-.106-.039-.134-.06-.149a.3.3,0,0,0-.206-.08.216.216,0,0,0-.16.049.193.193,0,0,0-.082.18v1.2a.26.26,0,0,1-.259.262H24.12a.26.26,0,0,1-.259-.262V33.961a.265.265,0,0,0-.092-.209A.242.242,0,0,0,23.6,33.7m2.53,4.847H24.5a.668.668,0,0,1-.482-.144.563.563,0,0,1-.155-.44V36.052a.26.26,0,0,1,.259-.262H26.6a.26.26,0,0,1,.259.262v1.906a.549.549,0,0,1-.234.454.811.811,0,0,1-.5.13m-1.745-.531a.733.733,0,0,0,.117.008h1.628a.423.423,0,0,0,.2-.028c.023-.016.023-.02.023-.032V36.314H24.379v1.645a.5.5,0,0,0,0,.053" transform="translate(-15.267 -21.881)" fill="#999"/>
|
||||
<path id="Path_14022" data-name="Path 14022" d="M110.236,33.72c.348,0,.524.158.524.473v1.413h1.283a.4.4,0,0,1,.451.45c0,.312-.149.467-.451.467H110.76v1.494h1.283a.4.4,0,0,1,.451.45c0,.312-.149.467-.451.467H110.76v.4a.459.459,0,0,1-.166.373.487.487,0,0,1-.358.141.5.5,0,0,1-.361-.151.476.476,0,0,1-.136-.366V34.2c0-.319.166-.477.5-.477m-5.279.222a2.7,2.7,0,0,1,2.135.809,2.62,2.62,0,0,1,.885,1.98,2.545,2.545,0,0,1-.892,1.943,2.665,2.665,0,0,1-2.129.809,2.99,2.99,0,0,1-2.324-.977,2.249,2.249,0,0,1-.723-1.776,2.675,2.675,0,0,1,.759-1.94,3.09,3.09,0,0,1,2.288-.849m0,.93a2.038,2.038,0,0,0-1.535.564,1.978,1.978,0,0,0,0,2.581,2.006,2.006,0,0,0,1.532.574,2.123,2.123,0,0,0,1.479-.463,2.1,2.1,0,0,0,.534-1.4,1.848,1.848,0,0,0-.4-1.255,2.258,2.258,0,0,0-1.611-.6m-2.122,5.79h6.529a1.553,1.553,0,0,1,1.081.379,1.145,1.145,0,0,1,.315.879v2.286a.517.517,0,0,1-.176.393.488.488,0,0,1-.348.124.5.5,0,0,1-.342-.121.551.551,0,0,1-.156-.4V41.923a.316.316,0,0,0-.073-.248.438.438,0,0,0-.305-.084h-6.526a.411.411,0,0,1-.471-.46c-.01-.312.146-.47.471-.47" transform="translate(-68.119 -22.402)" fill="#999"/>
|
||||
<path id="Path_14023" data-name="Path 14023" d="M109.715,44.466a.753.753,0,0,1-.51-.184.818.818,0,0,1-.246-.595V41.4a.463.463,0,0,0,0-.057.387.387,0,0,0-.116-.013h-6.525a.667.667,0,0,1-.73-.722.708.708,0,0,1,.178-.529.731.731,0,0,1,.552-.2h6.529a1.8,1.8,0,0,1,1.253.446,1.4,1.4,0,0,1,.4,1.074v2.286a.781.781,0,0,1-.26.586.739.739,0,0,1-.523.193m-7.4-4.061a.277.277,0,0,0-.18.043.238.238,0,0,0-.032.157c0,.159.03.206.213.206h6.525a.668.668,0,0,1,.483.155.567.567,0,0,1,.154.439v2.282a.287.287,0,0,0,.083.214.252.252,0,0,0,.156.042.231.231,0,0,0,.173-.055.255.255,0,0,0,.093-.2V41.4a.892.892,0,0,0-.232-.687,1.29,1.29,0,0,0-.906-.31Zm6.666.954,0,0,0,0m.734-1.766a.751.751,0,0,1-.541-.225.729.729,0,0,1-.215-.554V33.678a.687.687,0,0,1,.756-.738.7.7,0,0,1,.783.735v1.151h1.025a.653.653,0,0,1,.71.712.661.661,0,0,1-.71.728H110.5v.97h1.025a.653.653,0,0,1,.71.711.661.661,0,0,1-.71.728H110.5v.141a.784.784,0,0,1-.783.775m0-6.129c-.215,0-.239.069-.239.215v5.135c0,.124.04.161.053.174a.247.247,0,0,0,.364.014.21.21,0,0,0,.087-.184v-.4a.26.26,0,0,1,.259-.261h1.283c.149,0,.192-.027.192-.205,0-.145-.025-.188-.192-.188h-1.283a.26.26,0,0,1-.259-.262V36a.26.26,0,0,1,.259-.262h1.283c.149,0,.192-.027.192-.2,0-.148-.024-.188-.192-.188h-1.283a.26.26,0,0,1-.259-.262V33.675c0-.113,0-.211-.265-.211m-5.279,5.763a3.249,3.249,0,0,1-2.515-1.061,2.494,2.494,0,0,1-.791-1.953,2.945,2.945,0,0,1,.834-2.123,3.352,3.352,0,0,1,2.472-.928,2.955,2.955,0,0,1,2.328.9,2.868,2.868,0,0,1,.952,2.155,2.814,2.814,0,0,1-.978,2.137,2.9,2.9,0,0,1-2.3.877m0-5.541a2.822,2.822,0,0,0-2.106.774,2.4,2.4,0,0,0-.682,1.754,1.983,1.983,0,0,0,.634,1.579,2.74,2.74,0,0,0,2.154.912,2.433,2.433,0,0,0,1.934-.72,2.307,2.307,0,0,0,.828-1.771,2.35,2.35,0,0,0-.8-1.788,2.45,2.45,0,0,0-1.96-.739m0,4.649a2.262,2.262,0,0,1-1.719-.654,2.241,2.241,0,0,1,0-2.945,2.3,2.3,0,0,1,1.721-.643,2.518,2.518,0,0,1,1.788.674,2.112,2.112,0,0,1,.484,1.447,2,2,0,0,1-2.272,2.121m0-3.719a1.781,1.781,0,0,0-1.351.486,1.716,1.716,0,0,0,0,2.216,1.749,1.749,0,0,0,1.346.494,1.889,1.889,0,0,0,1.306-.4,1.816,1.816,0,0,0,.448-1.2,1.6,1.6,0,0,0-.337-1.082,1.988,1.988,0,0,0-1.417-.515" transform="translate(-67.597 -21.884)" fill="#999"/>
|
||||
<path id="Path_14024" data-name="Path 14024" d="M141.333,34.3h8.14a.538.538,0,0,1,.365.128.459.459,0,0,1,.146.326.5.5,0,0,1-.109.312.49.49,0,0,1-.365.151h-1.273l.076.047a.317.317,0,0,1,.07.064.465.465,0,0,1,.1.4l-.385,1.628h1.416a.414.414,0,0,1,.471.44c.017.319-.116.48-.408.48H141.28c-.288,0-.428-.158-.418-.47a.4.4,0,0,1,.458-.45h1.429l-.371-1.668a.492.492,0,0,1,.093-.409l.06-.057h-1.2a.41.41,0,0,1-.471-.46c-.01-.3.146-.456.471-.456m1.854.916.063.057a.527.527,0,0,1,.133.3l.365,1.776H147.1l.365-1.755a.428.428,0,0,1,.249-.366l.023-.013Zm-2.7,3.877h9.888a.443.443,0,0,1,.484.49q0,.4-.458.4h-4.473v.91l0,.06h2.656a1.362,1.362,0,0,1,.905.3.884.884,0,0,1,.351.738v1.678a1.056,1.056,0,0,1-.318.8,1.125,1.125,0,0,1-.839.322h-6.5a1.183,1.183,0,0,1-.859-.285A1.041,1.041,0,0,1,141,43.7V42.1a1.119,1.119,0,0,1,.325-.842,1.226,1.226,0,0,1,.872-.3h2.729l0-.034v-.936h-4.447q-.5,0-.5-.453c0-.292.169-.44.511-.44m1.936,2.779a.551.551,0,0,0-.312.057.418.418,0,0,0-.076.285v1.332c0,.134.017.218.056.252a.623.623,0,0,0,.371.077h5.922a.645.645,0,0,0,.332-.064.254.254,0,0,0,.086-.215V42.174c0-.111-.023-.181-.063-.208a.631.631,0,0,0-.378-.094Z" transform="translate(-93.565 -22.788)" fill="#999"/>
|
||||
<path id="Path_14025" data-name="Path 14025" d="M148.163,44.535h-6.5a1.431,1.431,0,0,1-1.039-.358,1.294,1.294,0,0,1-.4-.994v-1.6a1.374,1.374,0,0,1,.405-1.032,1.48,1.48,0,0,1,1.05-.371h2.468v-.447h-4.188a.71.71,0,1,1,.013-1.416h9.888a.7.7,0,0,1,.742.741.638.638,0,0,1-.716.675h-4.214v.447h2.394a1.612,1.612,0,0,1,1.071.362,1.143,1.143,0,0,1,.444.94v1.678a1.315,1.315,0,0,1-.4.985,1.375,1.375,0,0,1-1.017.394M141.677,40.7a.973.973,0,0,0-.7.229.855.855,0,0,0-.242.65v1.6a.782.782,0,0,0,.24.612.944.944,0,0,0,.685.217h6.5a.872.872,0,0,0,.656-.246.8.8,0,0,0,.243-.61V41.478a.625.625,0,0,0-.249-.53,1.122,1.122,0,0,0-.749-.249h-2.656a.257.257,0,0,1-.188-.082.264.264,0,0,1-.071-.194l0-.061v-.9a.26.26,0,0,1,.259-.261h4.473c.2,0,.2-.053.2-.141-.008-.194-.076-.228-.226-.228h-9.888c-.252,0-.252.083-.252.178s0,.191.239.191H144.4a.26.26,0,0,1,.259.261l0,.945a.263.263,0,0,1-.066.2.257.257,0,0,1-.192.086Zm6.191,2.92h-5.922a.813.813,0,0,1-.536-.138.565.565,0,0,1-.15-.453V41.7a.654.654,0,0,1,.147-.465.7.7,0,0,1,.5-.139h5.939a.866.866,0,0,1,.531.144.477.477,0,0,1,.169.419v1.423a.505.505,0,0,1-.187.422.862.862,0,0,1-.489.118m-6.09-.535a1.09,1.09,0,0,0,.168.011h5.922a.766.766,0,0,0,.157-.013l0-1.427c0-.006,0-.012,0-.017a.571.571,0,0,0-.182-.023h-5.939a1.052,1.052,0,0,0-.125.006.574.574,0,0,0,0,.075v1.332c0,.022,0,.041,0,.056m6.3-1.423,0,0,0,0m.978-3.648h-8.293a.66.66,0,0,1-.5-.189.732.732,0,0,1-.177-.551.653.653,0,0,1,.716-.7H141.9l-.3-1.349a.971.971,0,0,1-.01-.262h-.783a.667.667,0,0,1-.729-.722.686.686,0,0,1,.174-.515.735.735,0,0,1,.555-.2h8.14a.8.8,0,0,1,.534.191.73.73,0,0,1,.236.524.77.77,0,0,1-.164.474.758.758,0,0,1-.569.251h-.777a.8.8,0,0,1,0,.291l-.311,1.32h1.088a.672.672,0,0,1,.729.689.739.739,0,0,1-.169.564.651.651,0,0,1-.5.19m-8.253-.919c-.172,0-.2.045-.2.188a.28.28,0,0,0,.032.178.2.2,0,0,0,.127.03h8.293a.186.186,0,0,0,.121-.027.283.283,0,0,0,.028-.178c-.007-.144-.038-.191-.213-.191h-1.416a.258.258,0,0,1-.2-.1.264.264,0,0,1-.048-.223l.384-1.628a.191.191,0,0,0-.042-.166l-.083-.056a.127.127,0,1,0-.24,0l-.031.018c-.1.053-.109.1-.112.151a.242.242,0,0,1,0,.037l-.365,1.755a.26.26,0,0,1-.253.208h-3.349a.259.259,0,0,1-.253-.209l-.365-1.776a.3.3,0,0,0-.067-.175l-.048-.043a.264.264,0,0,1-.069-.288.259.259,0,0,1,.242-.168h4.546a.259.259,0,0,1,.25.194l0,.009s0-.008,0-.012a.259.259,0,0,1,.249-.191h1.273a.235.235,0,0,0,.182-.075.253.253,0,0,0,.033-.127.191.191,0,0,0-.07-.141.289.289,0,0,0-.182-.051h-8.14a.284.284,0,0,0-.183.043.217.217,0,0,0-.03.143c0,.162.028.207.213.207h1.2a.258.258,0,0,1,.24.165.264.264,0,0,1-.063.287l-.059.057a.264.264,0,0,0-.016.177l.368,1.653a.265.265,0,0,1-.05.221.258.258,0,0,1-.2.1Zm2.638-.524h2.929l.318-1.531a.745.745,0,0,1,.012-.08h-3.588c0,.02.008.041.01.062Z" transform="translate(-93.044 -22.269)" fill="#999"/>
|
||||
<path id="Path_14026" data-name="Path 14026" d="M32.18,32c-8.505,0-16.514-1.612-22.55-4.54C3.42,24.448,0,20.378,0,16S3.42,7.552,9.63,4.54C15.666,1.612,23.674,0,32.18,0S48.694,1.612,54.73,4.54c6.21,3.012,9.63,7.082,9.63,11.46s-3.42,8.448-9.63,11.46C48.694,30.388,40.685,32,32.18,32m0-30.49C23.893,1.51,16.114,3.07,10.275,5.9,4.611,8.649,1.492,12.235,1.492,16s3.119,7.351,8.783,10.1C16.114,28.93,23.893,30.49,32.18,30.49S48.246,28.93,54.085,26.1c5.664-2.747,8.783-6.333,8.783-10.1S59.749,8.649,54.085,5.9C48.246,3.07,40.467,1.51,32.18,1.51" transform="translate(0 0)" fill="#999"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 15 KiB |
BIN
backend/static/img/logo_geoyoung.ico
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
3
backend/static/img/logo_sooin.ico
Normal file
@ -0,0 +1,3 @@
|
||||
<script type="text/javascript">
|
||||
location.href = "./homepage/intro.asp";
|
||||
</script>
|
||||
4
backend/static/img/logo_sooin.svg
Normal file
@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<rect width="32" height="32" rx="6" fill="#7c3aed"/>
|
||||
<text x="16" y="22" text-anchor="middle" fill="white" font-family="Arial" font-weight="bold" font-size="16">수</text>
|
||||
</svg>
|
||||
BIN
backend/static/uploads/pets/pet_1_d4ffe983.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
backend/static/uploads/pets/pet_2_9919f990.jpg
Normal file
|
After Width: | Height: | Size: 1.3 MiB |
BIN
backend/static/uploads/pets/pet_3_53b73509.png
Normal file
|
After Width: | Height: | Size: 7.3 MiB |
BIN
backend/static/uploads/pets/pet_4_98a97580.jpg
Normal file
|
After Width: | Height: | Size: 4.3 MiB |
BIN
backend/static/uploads/pets/pet_5_f89b9542.jpg
Normal file
|
After Width: | Height: | Size: 1.2 MiB |