kdrug-inventory-system/add_mileage_system.py
시골약사 f3f1efd8c2 feat: 판매관리 시스템 Phase 1 및 마일리지 시스템 구현
- 판매 관리 기능 추가
  - compounds 테이블에 판매 관련 컬럼 추가 (payment_method, discount_rate, delivery_method 등)
  - 판매 상태 관리 (조제완료→결제대기→결제완료→배송대기→배송완료)
  - 판매 처리 모달 UI 구현
  - 9가지 상태별 뱃지 표시

- 마일리지 시스템 구축
  - patients 테이블에 마일리지 컬럼 추가 (balance, earned, used)
  - mileage_transactions 테이블 생성 (거래 이력 관리)
  - 마일리지 사용/적립 기능 구현

- 복합 결제 기능
  - 할인율(%) / 할인액(원) 직접 입력 선택 가능
  - 마일리지 + 현금 + 카드 + 계좌이체 복합 결제
  - 결제 금액 자동 검증
  - 결제 방법 자동 분류 (복합결제 지원)

- API 엔드포인트 추가
  - POST /api/compounds/<id>/status (상태 업데이트)
  - PUT /api/compounds/<id>/price (가격 조정)
  - GET /api/sales/statistics (판매 통계)

- 데이터베이스 설정 통합
  - config.py 생성하여 DB 경로 중앙화

TODO: 처방별 기본가격 정책 시스템 (price_policies 테이블 활용)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-18 05:42:29 +00:00

194 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""
마일리지 시스템 구축 - patients 테이블에 마일리지 컬럼 추가 및 이력 테이블 생성
"""
import sqlite3
from datetime import datetime
from config import DATABASE_PATH
def add_mileage_system():
"""환자 테이블에 마일리지 컬럼 추가 및 이력 테이블 생성"""
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
# 1. patients 테이블에 마일리지 관련 컬럼 추가
try:
cursor.execute("""
ALTER TABLE patients
ADD COLUMN mileage_balance INTEGER DEFAULT 0
""")
print("✓ mileage_balance 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- mileage_balance 컬럼 이미 존재")
else:
raise
try:
cursor.execute("""
ALTER TABLE patients
ADD COLUMN total_mileage_earned INTEGER DEFAULT 0
""")
print("✓ total_mileage_earned 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- total_mileage_earned 컬럼 이미 존재")
else:
raise
try:
cursor.execute("""
ALTER TABLE patients
ADD COLUMN total_mileage_used INTEGER DEFAULT 0
""")
print("✓ total_mileage_used 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- total_mileage_used 컬럼 이미 존재")
else:
raise
# 2. 마일리지 거래 이력 테이블 생성
cursor.execute("""
CREATE TABLE IF NOT EXISTS mileage_transactions (
transaction_id INTEGER PRIMARY KEY AUTOINCREMENT,
patient_id INTEGER REFERENCES patients(patient_id),
compound_id INTEGER REFERENCES compounds(compound_id),
transaction_type TEXT NOT NULL, -- EARNED, USED, EXPIRED, ADMIN_ADJUST
amount INTEGER NOT NULL,
balance_after INTEGER NOT NULL,
description TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_by TEXT
)
""")
print("✓ mileage_transactions 테이블 생성 완료")
# 인덱스 생성
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_mileage_transactions_patient
ON mileage_transactions(patient_id)
""")
print("✓ 인덱스 생성 완료")
# 3. compounds 테이블에 마일리지 사용 컬럼 추가
try:
cursor.execute("""
ALTER TABLE compounds
ADD COLUMN mileage_used INTEGER DEFAULT 0
""")
print("✓ compounds.mileage_used 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- compounds.mileage_used 컬럼 이미 존재")
else:
raise
try:
cursor.execute("""
ALTER TABLE compounds
ADD COLUMN mileage_earned INTEGER DEFAULT 0
""")
print("✓ compounds.mileage_earned 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- compounds.mileage_earned 컬럼 이미 존재")
else:
raise
# 4. 복합 결제를 위한 컬럼 추가
try:
cursor.execute("""
ALTER TABLE compounds
ADD COLUMN payment_cash INTEGER DEFAULT 0
""")
print("✓ payment_cash 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- payment_cash 컬럼 이미 존재")
else:
raise
try:
cursor.execute("""
ALTER TABLE compounds
ADD COLUMN payment_card INTEGER DEFAULT 0
""")
print("✓ payment_card 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- payment_card 컬럼 이미 존재")
else:
raise
try:
cursor.execute("""
ALTER TABLE compounds
ADD COLUMN payment_transfer INTEGER DEFAULT 0
""")
print("✓ payment_transfer 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- payment_transfer 컬럼 이미 존재")
else:
raise
try:
cursor.execute("""
ALTER TABLE compounds
ADD COLUMN discount_amount INTEGER DEFAULT 0
""")
print("✓ discount_amount 컬럼 추가 완료")
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e):
print("- discount_amount 컬럼 이미 존재")
else:
raise
conn.commit()
# 5. 테스트용 마일리지 데이터 추가 (박주호 회원)
cursor.execute("""
SELECT patient_id, name FROM patients
WHERE name LIKE '%박주호%' OR name LIKE '%주호%'
""")
patients = cursor.fetchall()
if patients:
for patient in patients:
print(f"\n박주호 회원 발견: ID={patient[0]}, 이름={patient[1]}")
# 초기 마일리지 부여
cursor.execute("""
UPDATE patients
SET mileage_balance = 50000,
total_mileage_earned = 50000,
total_mileage_used = 0
WHERE patient_id = ?
""", (patient[0],))
# 마일리지 이력 추가
cursor.execute("""
INSERT INTO mileage_transactions
(patient_id, transaction_type, amount, balance_after, description, created_by)
VALUES (?, 'ADMIN_ADJUST', 50000, 50000, '초기 마일리지 부여', 'system')
""", (patient[0],))
print(f" → 50,000 마일리지 부여 완료")
else:
print("\n박주호 회원을 찾을 수 없습니다.")
conn.commit()
# 현재 patients 테이블 구조 확인
cursor.execute("PRAGMA table_info(patients)")
columns = cursor.fetchall()
print("\n현재 patients 테이블 구조 (마일리지 관련):")
for col in columns:
if 'mileage' in col[1].lower():
print(f" - {col[1]}: {col[2]}")
conn.close()
print("\n마일리지 시스템 구축 완료!")
if __name__ == "__main__":
add_mileage_system()