- patient_query: 대체조제 원본 처방 제외 - rx_query: 대체조제 원본 처방 제외 - PS_Type=9는 대체조제시 원래 처방된 약(조제 안됨) - 기타 배치 스크립트 및 문서 추가
268 lines
7.3 KiB
Python
268 lines
7.3 KiB
Python
# -*- 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
|