#!/usr/bin/env python3 """ 삼소음 처방 추가 스크립트 처방 추가 가이드 문서의 방식에 따라 삼소음을 추가합니다. """ import sqlite3 from datetime import datetime def add_samsoeun(): """삼소음 처방 추가""" # 처방 데이터 준비 prescription_data = { 'formula_code': 'SSE001', # 삼소음 코드 'formula_name': '삼소음', 'formula_type': 'STANDARD', 'base_cheop': 1, 'base_pouches': 1, 'description': '리기화담, 해표산한의 효능으로 외감풍한과 내상식적으로 인한 기침, 가래를 치료하는 처방', 'ingredients': [ {'code': '3400H1AHM', 'herb': '인삼', 'amount': 4.0, 'notes': '대보원기'}, {'code': '3411H1AHM', 'herb': '소엽(자소엽)', 'amount': 4.0, 'notes': '해표산한'}, {'code': '3433H1AHM', 'herb': '전호', 'amount': 4.0, 'notes': '강기화담'}, {'code': '3182H1AHM', 'herb': '반하', 'amount': 4.0, 'notes': '화담지구'}, {'code': '3002H1AHM', 'herb': '갈근', 'amount': 4.0, 'notes': '승진해기'}, {'code': '3215H1AHM', 'herb': '적복령(복령)', 'amount': 4.0, 'notes': '건비이수'}, {'code': '3115H1AHM', 'herb': '대조(대추)', 'amount': 4.0, 'notes': '보중익기'}, {'code': '3466H1AHM', 'herb': '진피', 'amount': 3.0, 'notes': '리기화담'}, {'code': '3077H1AHM', 'herb': '길경', 'amount': 3.0, 'notes': '선폐거담'}, {'code': '3454H1AHM', 'herb': '지각', 'amount': 3.0, 'notes': '파기소적'}, {'code': '3007H1AHM', 'herb': '감초', 'amount': 3.0, 'notes': '조화제약'}, {'code': '3017H1AHM', 'herb': '건강', 'amount': 1.0, 'notes': '온중산한'} ] } conn = sqlite3.connect('database/kdrug.db') cursor = conn.cursor() try: # 기존 삼소음 처방 확인 cursor.execute(""" SELECT formula_id, formula_code, formula_name FROM formulas WHERE formula_code = ? OR formula_name = ? """, (prescription_data['formula_code'], prescription_data['formula_name'])) existing = cursor.fetchone() if existing: print(f"⚠️ 이미 존재하는 처방: {existing[2]} ({existing[1]})") print("기존 처방을 삭제하고 새로 추가하시겠습니까? (이 스크립트는 자동으로 진행합니다)") # 기존 처방과 관련 데이터 삭제 cursor.execute("DELETE FROM formula_ingredients WHERE formula_id = ?", (existing[0],)) cursor.execute("DELETE FROM formulas WHERE formula_id = ?", (existing[0],)) print(f"✅ 기존 처방 삭제 완료") print(f"\n{'='*60}") print(f"📝 {prescription_data['formula_name']} 처방 추가 중...") # 1. formulas 테이블에 처방 추가 cursor.execute(""" INSERT INTO formulas ( formula_code, formula_name, formula_type, base_cheop, base_pouches, description, is_active, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) """, ( prescription_data['formula_code'], prescription_data['formula_name'], prescription_data['formula_type'], prescription_data['base_cheop'], prescription_data['base_pouches'], prescription_data['description'] )) formula_id = cursor.lastrowid print(f"✅ 처방 기본 정보 등록 (ID: {formula_id})") # 2. formula_ingredients 테이블에 약재 추가 print(f"\n약재 구성:") sort_order = 0 total_amount = 0 for ingredient in prescription_data['ingredients']: cursor.execute(""" INSERT INTO formula_ingredients ( formula_id, ingredient_code, grams_per_cheop, notes, sort_order, created_at ) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP) """, ( formula_id, ingredient['code'], ingredient['amount'], ingredient['notes'], sort_order )) sort_order += 1 total_amount += ingredient['amount'] print(f" - {ingredient['herb']:15s}: {ingredient['amount']:5.1f}g ({ingredient['notes']})") print(f"\n총 약재: {len(prescription_data['ingredients'])}개") print(f"1첩 총 용량: {total_amount:.1f}g") conn.commit() print(f"\n✅ {prescription_data['formula_name']} 처방 추가 완료!") # 추가된 처방 확인 print(f"\n{'='*60}") print("📊 추가된 처방 확인:") cursor.execute(""" SELECT f.formula_id, f.formula_code, f.formula_name, COUNT(fi.ingredient_id) as herb_count, SUM(fi.grams_per_cheop) as total_grams FROM formulas f LEFT JOIN formula_ingredients fi ON f.formula_id = fi.formula_id WHERE f.formula_code = ? GROUP BY f.formula_id """, (prescription_data['formula_code'],)) result = cursor.fetchone() if result: print(f"ID {result[0]}: {result[1]} - {result[2]}") print(f" 약재 {result[3]}개, 총 {result[4]:.1f}g") # 상세 구성 확인 print(f"\n상세 구성:") cursor.execute(""" SELECT hm.herb_name, fi.grams_per_cheop, fi.notes FROM formula_ingredients fi JOIN herb_masters hm ON fi.ingredient_code = hm.ingredient_code WHERE fi.formula_id = ? ORDER BY fi.sort_order """, (result[0],)) for herb, amount, notes in cursor.fetchall(): print(f" - {herb:15s}: {amount:5.1f}g ({notes})") except sqlite3.IntegrityError as e: print(f"❌ 중복 오류: {e}") conn.rollback() return False except sqlite3.Error as e: print(f"❌ 데이터베이스 오류: {e}") conn.rollback() return False finally: conn.close() return True if __name__ == "__main__": print("🌿 삼소음 처방 추가 프로그램") print("="*60) if add_samsoeun(): print("\n✅ 삼소음 처방 추가 작업이 완료되었습니다.") else: print("\n❌ 처방 추가 중 오류가 발생했습니다.")