diff --git a/add_prescription_data.py b/add_prescription_data.py new file mode 100644 index 0000000..6062dd3 --- /dev/null +++ b/add_prescription_data.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +처방 데이터 추가 스크립트 +- 소청룡탕, 갈근탕 등 처방 데이터 추가 +""" + +import sqlite3 +from datetime import datetime + +def get_connection(): + """데이터베이스 연결""" + return sqlite3.connect('database/kdrug.db') + +def add_prescriptions(): + """소청룡탕과 갈근탕 처방 추가""" + conn = get_connection() + cursor = conn.cursor() + + # 처방 데이터 정의 + prescriptions = [ + { + 'formula_code': 'SCR001', + 'formula_name': '소청룡탕', + 'formula_type': 'STANDARD', + 'base_cheop': 1, + 'base_pouches': 1, + 'description': '외감풍한, 내정수음으로 인한 기침, 천식을 치료하는 처방. 한담을 풀어내고 기침을 멎게 함.', + 'ingredients': [ + {'code': '3147H1AHM', 'amount': 6.0, 'notes': '발한해표'}, # 마황 + {'code': '3419H1AHM', 'amount': 6.0, 'notes': '화영지통'}, # 백작약 + {'code': '3342H1AHM', 'amount': 6.0, 'notes': '렴폐지해'}, # 오미자 + {'code': '3182H1AHM', 'amount': 6.0, 'notes': '화담지구'}, # 반하 + {'code': '3285H1AHM', 'amount': 4.0, 'notes': '온폐산한'}, # 세신 + {'code': '3017H1AHM', 'amount': 4.0, 'notes': '온중산한'}, # 건강 + {'code': '3033H1AHM', 'amount': 4.0, 'notes': '해표발한'}, # 계지 + {'code': '3007H1AHM', 'amount': 4.0, 'notes': '조화제약'}, # 감초 + ] + }, + { + 'formula_code': 'GGT001', + 'formula_name': '갈근탕', + 'formula_type': 'STANDARD', + 'base_cheop': 1, + 'base_pouches': 1, + 'description': '외감풍한으로 인한 두통, 발열, 오한, 항강을 치료하는 처방. 발한해표하고 승진해기함.', + 'ingredients': [ + {'code': '3002H1AHM', 'amount': 8.0, 'notes': '승진해기'}, # 갈근 + {'code': '3147H1AHM', 'amount': 6.0, 'notes': '발한해표'}, # 마황 + {'code': '3115H1AHM', 'amount': 6.0, 'notes': '보중익기'}, # 대조(대추) + {'code': '3033H1AHM', 'amount': 4.0, 'notes': '해표발한'}, # 계지 + {'code': '3419H1AHM', 'amount': 4.0, 'notes': '화영지통'}, # 작약 + {'code': '3007H1AHM', 'amount': 4.0, 'notes': '조화제약'}, # 감초 + {'code': '3017H1AHM', 'amount': 2.0, 'notes': '온중산한'}, # 건강 + ] + } + ] + + try: + for prescription in prescriptions: + # 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['formula_code'], + prescription['formula_name'], + prescription['formula_type'], + prescription['base_cheop'], + prescription['base_pouches'], + prescription['description'] + )) + + formula_id = cursor.lastrowid + print(f"[추가됨] {prescription['formula_name']} 처방 추가 완료 (ID: {formula_id})") + + # 2. formula_ingredients 테이블에 구성 약재 추가 + for ingredient in prescription['ingredients']: + # 약재 이름 조회 (로그용) + cursor.execute(""" + SELECT herb_name FROM herb_masters + WHERE ingredient_code = ? + """, (ingredient['code'],)) + herb_name_result = cursor.fetchone() + herb_name = herb_name_result[0] if herb_name_result else 'Unknown' + + cursor.execute(""" + INSERT INTO formula_ingredients ( + formula_id, ingredient_code, grams_per_cheop, notes, + sort_order, created_at + ) VALUES (?, ?, ?, ?, 0, CURRENT_TIMESTAMP) + """, ( + formula_id, + ingredient['code'], + ingredient['amount'], + ingredient['notes'] + )) + + print(f" - {herb_name}({ingredient['code']}): {ingredient['amount']}g - {ingredient['notes']}") + + conn.commit() + print("\n[완료] 모든 처방 데이터가 성공적으로 추가되었습니다!") + + except Exception as e: + conn.rollback() + print(f"\n[오류] 오류 발생: {e}") + import traceback + traceback.print_exc() + finally: + conn.close() + +def verify_prescriptions(): + """추가된 처방 데이터 확인""" + conn = get_connection() + cursor = conn.cursor() + + print("\n" + "="*80) + print("추가된 처방 데이터 확인") + print("="*80) + + # 추가된 처방 목록 확인 + cursor.execute(""" + SELECT f.formula_id, f.formula_code, f.formula_name, f.formula_type, f.description, + COUNT(fi.ingredient_id) as ingredient_count, + SUM(fi.grams_per_cheop) as total_amount + FROM formulas f + LEFT JOIN formula_ingredients fi ON f.formula_id = fi.formula_id + WHERE f.formula_code IN ('SCR001', 'GGT001') + GROUP BY f.formula_id + """) + + for row in cursor.fetchall(): + print(f"\n[처방] {row[2]} ({row[1]})") + print(f" 타입: {row[3]}") + print(f" 설명: {row[4]}") + print(f" 구성약재: {row[5]}가지") + print(f" 총 용량: {row[6]}g") + + # 구성 약재 상세 + cursor.execute(""" + SELECT hm.herb_name, fi.ingredient_code, 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.grams_per_cheop DESC + """, (row[0],)) + + print(" 구성 약재:") + for ingredient in cursor.fetchall(): + print(f" - {ingredient[0]}({ingredient[1]}): {ingredient[2]}g - {ingredient[3]}") + + conn.close() + +def main(): + print("="*80) + print("처방 데이터 추가 스크립트") + print("="*80) + + # 처방 추가 + add_prescriptions() + + # 추가된 데이터 확인 + verify_prescriptions() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/add_sample_herb_data.py b/add_sample_herb_data.py index cec7e2c..019443d 100644 --- a/add_sample_herb_data.py +++ b/add_sample_herb_data.py @@ -1,8 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ -한약재 샘플 데이터 추가 스크립트 -주요 약재들의 확장 정보와 효능 태그를 추가합니다. +한약재 샘플 데이터 추가 - 십전대보탕 구성 약재 """ import sqlite3 @@ -17,171 +16,173 @@ def add_herb_extended_data(): conn = get_connection() cursor = conn.cursor() - # 주요 약재들의 확장 정보 - herbs_data = [ + # 십전대보탕 구성 약재들의 실제 ingredient_code 사용 + herb_data = [ { 'ingredient_code': '3400H1AHM', # 인삼 - 'property': '온', - 'taste': '감,미고', - 'meridian_tropism': '비,폐,심', - 'main_effects': '대보원기, 보비익폐, 생진지갈, 안신증지', - 'indications': '기허증, 비허증, 폐허증, 심기허증, 진액부족, 당뇨병', - 'contraindications': '실증, 열증, 음허화왕', - 'precautions': '복용 중 무 섭취 금지, 고혈압 환자 주의', - 'dosage_range': '3-9g', - 'dosage_max': '30g', - 'active_compounds': '인삼사포닌(ginsenoside Rb1, Rg1, Rg3), 다당체, 아미노산', - 'pharmacological_effects': '면역증강, 항피로, 항산화, 혈당조절, 인지능력개선', - 'clinical_applications': '만성피로, 면역력저하, 당뇨병 보조치료, 노인성 인지저하', - 'tags': [('보기', 5), ('보양', 4), ('안신', 3), ('진통', 2)] + 'property': '온(溫)', + 'taste': '감(甘), 미고(微苦)', + 'meridian_tropism': '폐(肺), 비(脾), 심(心)', + 'main_effects': '대보원기, 보비익폐, 생진지갈, 안신익지', + 'indications': '기허증, 피로, 식욕부진, 설사, 호흡곤란, 자한, 양위, 소갈, 건망, 불면', + 'dosage_range': '1~3돈(3~9g)', + 'precautions': '실증, 열증자 신중 투여', + 'preparation_method': '수치법: 홍삼, 백삼, 당삼 등으로 가공', + 'tags': [ + ('보기', 5), + ('보혈', 3), + ('안신', 4), + ] }, { - 'ingredient_code': '3400H1ADL', # 감초 - 'property': '평', - 'taste': '감', - 'meridian_tropism': '비,위,폐,심', - 'main_effects': '보비익기, 청열해독, 거담지해, 완급지통, 조화제약', - 'indications': '비허증, 해수, 인후통, 소화성궤양, 경련성 통증', - 'contraindications': '습증, 수종, 고혈압', - 'precautions': '장기복용 시 부종 주의, 칼륨 감소 주의', - 'dosage_range': '2-10g', - 'dosage_max': '30g', - 'active_compounds': 'glycyrrhizin, liquiritin, flavonoid, triterpenoid', - 'pharmacological_effects': '항염증, 항궤양, 간보호, 진해거담, 항알레르기', - 'clinical_applications': '위염, 위궤양, 기관지염, 약물조화, 간염', - 'tags': [('보기', 3), ('청열', 3), ('해독', 4), ('거담', 3), ('항염', 4)] + 'ingredient_code': '3007H1AHM', # 감초 + 'property': '평(平)', + 'taste': '감(甘)', + 'meridian_tropism': '심(心), 폐(肺), 비(脾), 위(胃)', + 'main_effects': '화중완급, 윤폐지해, 해독', + 'indications': '복통, 기침, 인후통, 소화불량, 약물중독', + 'dosage_range': '1~3돈(3~9g)', + 'precautions': '장기복용시 부종 주의', + 'preparation_method': '자감초(炙甘草) 등', + 'tags': [ + ('보기', 3), + ('해독', 4), + ('윤조', 3), + ('청열', 2), + ('항염', 3), + ] }, { - 'ingredient_code': '3400H1ACD', # 당귀 - 'property': '온', - 'taste': '감,신', - 'meridian_tropism': '간,심,비', - 'main_effects': '보혈활혈, 조경지통, 윤장통변', - 'indications': '혈허증, 월경부조, 무월경, 변비, 타박상', - 'contraindications': '설사, 습성체질', - 'precautions': '과량 복용 시 설사 주의', - 'dosage_range': '5-15g', - 'dosage_max': '30g', - 'active_compounds': 'ligustilide, n-butylidene phthalide, ferulic acid', - 'pharmacological_effects': '혈액순환개선, 항혈전, 자궁수축조절, 진정진통', - 'clinical_applications': '빈혈, 월경불순, 산후조리, 혈액순환장애', - 'tags': [('보혈', 5), ('활혈', 5), ('진통', 3)] + 'ingredient_code': '3204H1AHM', # 백출 + 'property': '온(溫)', + 'taste': '감(甘), 고(苦)', + 'meridian_tropism': '비(脾), 위(胃)', + 'main_effects': '건비익기, 조습이수, 지한, 안태', + 'indications': '비허설사, 수종, 담음, 자한, 태동불안', + 'dosage_range': '2~4돈(6~12g)', + 'precautions': '음허내열자 신중', + 'preparation_method': '토백출, 생백출', + 'tags': [ + ('보기', 4), + ('이수', 4), + ('건비', 5), + ] }, { - 'ingredient_code': '3400H1AGN', # 황기 - 'property': '온', - 'taste': '감', - 'meridian_tropism': '비,폐', - 'main_effects': '보기승양, 고표지한, 이수소종, 탁독배농', - 'indications': '기허증, 자한, 부종, 탈항, 자궁탈수', - 'contraindications': '표실증, 음허화왕', - 'precautions': '감기 초기 금지', - 'dosage_range': '10-30g', - 'dosage_max': '60g', - 'active_compounds': 'astragaloside, polysaccharide, flavonoid', - 'pharmacological_effects': '면역조절, 항바이러스, 항산화, 신기능보호', - 'clinical_applications': '면역력저하, 만성신장염, 당뇨병, 심부전', - 'tags': [('보기', 5), ('이수', 3), ('해표', 2)] + 'ingredient_code': '3215H1AHM', # 복령 + 'property': '평(平)', + 'taste': '감(甘), 담(淡)', + 'meridian_tropism': '심(心), 폐(肺), 비(脾), 신(腎)', + 'main_effects': '이수삼습, 건비영심, 안신', + 'indications': '소변불리, 수종, 설사, 불면, 심계', + 'dosage_range': '3~5돈(9~15g)', + 'precautions': '음허자 신중', + 'preparation_method': '백복령, 적복령', + 'tags': [ + ('이수', 5), + ('안신', 3), + ('건비', 3), + ] }, { - 'ingredient_code': '3400H1AEW', # 작약 - 'property': '량', - 'taste': '고,산', - 'meridian_tropism': '간,비', - 'main_effects': '양혈조경, 유간지통, 렴음지한', - 'indications': '혈허증, 월경부조, 간혈부족, 자한도한', - 'contraindications': '양허설사', - 'precautions': '한성약물과 병용 주의', - 'dosage_range': '6-15g', - 'dosage_max': '30g', - 'active_compounds': 'paeoniflorin, albiflorin, benzoic acid', - 'pharmacological_effects': '진정진통, 항경련, 항염증, 면역조절', - 'clinical_applications': '월경통, 근육경련, 두통, 자가면역질환', - 'tags': [('보혈', 4), ('평간', 4), ('진통', 4)] + 'ingredient_code': '3419H1AHM', # 작약 + 'property': '미한(微寒)', + 'taste': '고(苦), 산(酸)', + 'meridian_tropism': '간(肝), 비(脾)', + 'main_effects': '양혈렴음, 유간지통, 평간양', + 'indications': '혈허, 복통, 사지경련, 두훈, 월경불순', + 'dosage_range': '2~4돈(6~12g)', + 'precautions': '비허설사자 신중', + 'preparation_method': '백작약, 적작약', + 'tags': [ + ('보혈', 4), + ('진경', 4), + ('평간', 3), + ] }, { - 'ingredient_code': '3400H1ACF', # 천궁 - 'property': '온', - 'taste': '신', - 'meridian_tropism': '간,담,심포', + 'ingredient_code': '3475H1AHM', # 천궁 + 'property': '온(溫)', + 'taste': '신(辛)', + 'meridian_tropism': '간(肝), 담(膽), 심포(心包)', 'main_effects': '활혈행기, 거풍지통', - 'indications': '혈어증, 두통, 월경불순, 풍습비통', - 'contraindications': '음허화왕, 월경과다', - 'precautions': '출혈 경향 환자 주의', - 'dosage_range': '3-10g', - 'dosage_max': '15g', - 'active_compounds': 'ligustilide, senkyunolide, ferulic acid', - 'pharmacological_effects': '혈관확장, 항혈전, 진정진통, 항염증', - 'clinical_applications': '편두통, 혈관성 두통, 어혈증, 월경통', - 'tags': [('활혈', 5), ('이기', 4), ('진통', 5)] + 'indications': '혈체, 두통, 현훈, 월경불순, 복통', + 'dosage_range': '1~2돈(3~6g)', + 'precautions': '음허화왕자 신중', + 'preparation_method': '주천궁', + 'tags': [ + ('활혈', 5), + ('거풍', 3), + ('지통', 4), + ] }, { - 'ingredient_code': '3400H1ACG', # 지황(숙지황) - 'property': '온', - 'taste': '감', - 'meridian_tropism': '간,신', - 'main_effects': '보혈자음, 익정전수', - 'indications': '혈허증, 간신음허, 수발조백, 유정도한', - 'contraindications': '비허설사, 담습', - 'precautions': '소화불량 주의', - 'dosage_range': '10-30g', - 'dosage_max': '60g', - 'active_compounds': 'catalpol, rehmannioside, aucubin', - 'pharmacological_effects': '조혈촉진, 면역조절, 혈당강하, 신경보호', - 'clinical_applications': '빈혈, 당뇨병, 치매예방, 불임증', - 'tags': [('보혈', 5), ('보음', 5)] + 'ingredient_code': '3105H1AHM', # 당귀 + 'property': '온(溫)', + 'taste': '감(甘), 신(辛)', + 'meridian_tropism': '간(肝), 심(心), 비(脾)', + 'main_effects': '보혈활혈, 조경지통, 윤장통변', + 'indications': '혈허, 월경불순, 복통, 변비, 타박상', + 'dosage_range': '2~4돈(6~12g)', + 'precautions': '습성설사자 신중', + 'preparation_method': '주당귀, 당귀신, 당귀미', + 'tags': [ + ('보혈', 5), + ('활혈', 4), + ('윤조', 3), + ] }, { - 'ingredient_code': '3400H1AFJ', # 백출 - 'property': '온', - 'taste': '고,감', - 'meridian_tropism': '비,위', - 'main_effects': '건비익기, 조습이수, 지한안태', - 'indications': '비허증, 식욕부진, 설사, 수종, 자한', - 'contraindications': '음허조갈', - 'precautions': '진액부족 시 주의', - 'dosage_range': '6-15g', - 'dosage_max': '30g', - 'active_compounds': 'atractylenolide, atractylon', - 'pharmacological_effects': '위장운동촉진, 이뇨, 항염증, 항종양', - 'clinical_applications': '만성설사, 부종, 임신오조', - 'tags': [('보기', 4), ('이수', 4), ('소화', 3)] + 'ingredient_code': '3583H1AHM', # 황기 + 'property': '온(溫)', + 'taste': '감(甘)', + 'meridian_tropism': '폐(肺), 비(脾)', + 'main_effects': '보기승양, 고표지한, 이수소종, 탈독생기', + 'indications': '기허, 자한, 설사, 탈항, 수종, 창양', + 'dosage_range': '3~6돈(9~18g)', + 'precautions': '표실사 및 음허자 신중', + 'preparation_method': '밀자황기', + 'tags': [ + ('보기', 5), + ('승양', 4), + ('고표', 4), + ] }, { - 'ingredient_code': '3400H1AGM', # 복령 - 'property': '평', - 'taste': '감,담', - 'meridian_tropism': '심,비,폐,신', - 'main_effects': '이수삼습, 건비안신', - 'indications': '수종, 소변불리, 비허설사, 불면, 심계', - 'contraindications': '음허진액부족', - 'precautions': '이뇨제와 병용 주의', - 'dosage_range': '10-15g', - 'dosage_max': '30g', - 'active_compounds': 'pachymic acid, polysaccharide', - 'pharmacological_effects': '이뇨, 진정, 항염증, 면역조절', - 'clinical_applications': '부종, 불면증, 만성설사', - 'tags': [('이수', 5), ('안신', 3), ('보기', 2)] + 'ingredient_code': '3384H1AHM', # 육계 + 'property': '대열(大熱)', + 'taste': '감(甘), 신(辛)', + 'meridian_tropism': '신(腎), 비(脾), 심(心), 간(肝)', + 'main_effects': '보화조양, 산한지통, 온경통맥', + 'indications': '양허, 냉증, 요통, 복통, 설사', + 'dosage_range': '0.5~1돈(1.5~3g)', + 'precautions': '음허화왕자, 임신부 금기', + 'preparation_method': '육계심, 계피', + 'tags': [ + ('보양', 5), + ('온리', 5), + ('산한', 4), + ] }, { - 'ingredient_code': '3400H1AGI', # 반하 - 'property': '온', - 'taste': '신', - 'meridian_tropism': '비,위,폐', - 'main_effects': '조습화담, 강역지구, 소비산결', - 'indications': '습담, 구토, 해수담다, 현훈', - 'contraindications': '음허조해, 임신', - 'precautions': '임산부 금기, 생품 독성 주의', - 'dosage_range': '5-10g', - 'dosage_max': '15g', - 'active_compounds': 'ephedrine, β-sitosterol', - 'pharmacological_effects': '진토, 진해거담, 항종양', - 'clinical_applications': '임신오조, 기관지염, 현훈증', - 'tags': [('거담', 5), ('소화', 3)] - } + 'ingredient_code': '3299H1AHM', # 숙지황 + 'property': '온(溫)', + 'taste': '감(甘)', + 'meridian_tropism': '간(肝), 신(腎)', + 'main_effects': '자음보혈, 익정전수', + 'indications': '혈허, 음허, 요슬산연, 유정, 붕루', + 'dosage_range': '3~6돈(9~18g)', + 'precautions': '비허설사, 담다자 신중', + 'preparation_method': '숙지황 제법', + 'tags': [ + ('보혈', 5), + ('자음', 5), + ('보신', 4), + ] + }, ] - for herb in herbs_data: + for herb in herb_data: # herb_master_extended 업데이트 cursor.execute(""" UPDATE herb_master_extended @@ -190,53 +191,49 @@ def add_herb_extended_data(): meridian_tropism = ?, main_effects = ?, indications = ?, - contraindications = ?, - precautions = ?, dosage_range = ?, - dosage_max = ?, - active_compounds = ?, - pharmacological_effects = ?, - clinical_applications = ?, + precautions = ?, + preparation_method = ?, updated_at = CURRENT_TIMESTAMP WHERE ingredient_code = ? """, ( - herb['property'], herb['taste'], herb['meridian_tropism'], - herb['main_effects'], herb['indications'], herb['contraindications'], - herb['precautions'], herb['dosage_range'], herb['dosage_max'], - herb['active_compounds'], herb['pharmacological_effects'], - herb['clinical_applications'], herb['ingredient_code'] + herb['property'], + herb['taste'], + herb['meridian_tropism'], + herb['main_effects'], + herb['indications'], + herb['dosage_range'], + herb['precautions'], + herb['preparation_method'], + herb['ingredient_code'] )) - # herb_id 조회 - cursor.execute(""" - SELECT herb_id FROM herb_master_extended - WHERE ingredient_code = ? - """, (herb['ingredient_code'],)) + # 효능 태그 매핑 + for tag_name, strength in herb.get('tags', []): + # 태그 ID 조회 + cursor.execute(""" + SELECT tag_id FROM herb_efficacy_tags + WHERE tag_name = ? + """, (tag_name,)) - result = cursor.fetchone() - if result: - herb_id = result[0] + tag_result = cursor.fetchone() + if tag_result: + tag_id = tag_result[0] - # 효능 태그 매핑 - for tag_name, strength in herb.get('tags', []): - # 태그 ID 조회 + # 기존 태그 삭제 cursor.execute(""" - SELECT tag_id FROM herb_efficacy_tags - WHERE tag_name = ? - """, (tag_name,)) + DELETE FROM herb_item_tags + WHERE ingredient_code = ? AND tag_id = ? + """, (herb['ingredient_code'], tag_id)) - tag_result = cursor.fetchone() - if tag_result: - tag_id = tag_result[0] + # 태그 매핑 추가 + cursor.execute(""" + INSERT INTO herb_item_tags + (ingredient_code, tag_id, strength) + VALUES (?, ?, ?) + """, (herb['ingredient_code'], tag_id, strength)) - # 태그 매핑 추가 - cursor.execute(""" - INSERT OR REPLACE INTO herb_item_tags - (herb_id, tag_id, strength) - VALUES (?, ?, ?) - """, (herb_id, tag_id, strength)) - - print(f"✅ {herb['ingredient_code']} 데이터 추가 완료") + print(f"✅ {herb['ingredient_code']} 데이터 추가 완료") conn.commit() conn.close() @@ -248,85 +245,64 @@ def add_prescription_rules(): # 몇 가지 대표적인 배합 규칙 추가 rules = [ - # 상수(相須) - 서로 도와서 효과를 증강 { - 'herb1': '인삼', 'herb2': '황기', - 'relationship': '상수', - 'description': '두 약재가 함께 사용되면 보기 효과가 증강됨', - 'severity': 0 + 'herb1': '인삼', + 'herb2': '황기', + 'rule_type': '상수', + 'description': '보기작용 상승효과', + 'clinical_note': '기허증에 병용시 효과 증대' }, { - 'herb1': '당귀', 'herb2': '천궁', - 'relationship': '상수', - 'description': '혈액순환 개선 효과가 증강됨', - 'severity': 0 - }, - # 상사(相使) - 한 약이 다른 약의 효능을 도움 - { - 'herb1': '반하', 'herb2': '생강', - 'relationship': '상사', - 'description': '생강이 반하의 독성을 감소시킴', - 'severity': 0 - }, - # 상반(相反) - 함께 사용하면 독성이나 부작용 발생 - { - 'herb1': '감초', 'herb2': '감수', - 'relationship': '상반', - 'description': '십팔반(十八反) - 함께 사용 금기', - 'severity': 5, - 'is_absolute': True + 'herb1': '당귀', + 'herb2': '천궁', + 'rule_type': '상수', + 'description': '활혈작용 상승효과', + 'clinical_note': '혈허, 혈체에 병용' }, { - 'herb1': '인삼', 'herb2': '오령지', - 'relationship': '상반', - 'description': '십구외(十九畏) - 함께 사용 주의', - 'severity': 4, - 'is_absolute': False + 'herb1': '반하', + 'herb2': '생강', + 'rule_type': '상수', + 'description': '반하의 독성 감소, 진토작용 증강', + 'clinical_note': '구토, 오심에 병용' + }, + { + 'herb1': '감초', + 'herb2': '감수', + 'rule_type': '상반', + 'description': '효능 상반', + 'clinical_note': '병용 금지' + }, + { + 'herb1': '인삼', + 'herb2': '오령지', + 'rule_type': '상외', + 'description': '효능 감소', + 'clinical_note': '병용시 주의' } ] for rule in rules: - # herb_id 조회 cursor.execute(""" - SELECT herb_id FROM herb_master_extended - WHERE name_korean = ? - """, (rule['herb1'],)) - herb1_result = cursor.fetchone() - - cursor.execute(""" - SELECT herb_id FROM herb_master_extended - WHERE name_korean = ? - """, (rule['herb2'],)) - herb2_result = cursor.fetchone() - - if herb1_result and herb2_result: - cursor.execute(""" - INSERT OR REPLACE INTO prescription_rules - (herb1_id, herb2_id, relationship_type, description, - severity_level, is_absolute) - VALUES (?, ?, ?, ?, ?, ?) - """, ( - herb1_result[0], herb2_result[0], - rule['relationship'], rule['description'], - rule['severity'], rule.get('is_absolute', False) - )) - print(f"✅ {rule['herb1']} - {rule['herb2']} 규칙 추가") + INSERT OR IGNORE INTO prescription_rules + (herb1_name, herb2_name, rule_type, description, clinical_notes) + VALUES (?, ?, ?, ?, ?) + """, (rule['herb1'], rule['herb2'], rule['rule_type'], + rule['description'], rule['clinical_note'])) + print(f"✅ {rule['herb1']} - {rule['herb2']} 규칙 추가") conn.commit() conn.close() def main(): - """메인 실행 함수""" - print("\n" + "="*80) - print("한약재 샘플 데이터 추가") - print("="*80 + "\n") + print("=" * 80) + print("한약재 샘플 데이터 추가 - 십전대보탕 구성 약재") + print("=" * 80) try: - # 1. 약재 확장 정보 및 태그 추가 - print("1. 약재 확장 정보 추가 중...") + print("\n1. 약재 확장 정보 추가 중...") add_herb_extended_data() - # 2. 처방 규칙 추가 print("\n2. 처방 배합 규칙 추가 중...") add_prescription_rules() diff --git a/add_wolbitang_prescriptions.py b/add_wolbitang_prescriptions.py new file mode 100644 index 0000000..ac5c0ef --- /dev/null +++ b/add_wolbitang_prescriptions.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +""" +월비탕 단계별 처방 추가 스크립트 + +월비탕 1차부터 4차까지 단계별로 처방을 등록합니다. +각 단계마다 약재의 용량이 다릅니다. +""" + +import sqlite3 +import json +from datetime import datetime + +def add_wolbitang_prescriptions(): + """월비탕 단계별 처방 추가""" + + # 월비탕 단계별 데이터 + wolbitang_data = { + "월비탕 1차": { + "마황": 4, + "석고": 3, + "감초": 3, + "진피": 3.333, + "복령": 4, + "갈근": 3.333, + "건지황": 3.333, + "창출": 3.333 + }, + "월비탕 2차": { + "마황": 5, + "석고": 4, + "감초": 3, + "진피": 3.75, + "복령": 4, + "갈근": 3.333, + "건지황": 3.333, + "창출": 3.333 + }, + "월비탕 3차": { + "마황": 6, + "석고": 4.17, + "감초": 3, + "진피": 4.17, + "복령": 4.17, + "갈근": 3.75, + "건지황": 3.75, + "창출": 3.333 + }, + "월비탕 4차": { + "마황": 7, + "석고": 5, + "감초": 3, + "진피": 4.17, + "복령": 5, + "갈근": 3.75, + "건지황": 4, + "창출": 3.333 + } + } + + conn = sqlite3.connect('kdrug.db') + cursor = conn.cursor() + + try: + # 약재명-코드 매핑 + herb_code_mapping = { + "마황": "H004", + "석고": "H025", + "감초": "H001", + "진피": "H022", + "복령": "H010", + "갈근": "H024", + "건지황": "H026", + "창출": "H014" + } + + # 각 단계별로 처방 추가 + for prescription_name, herbs in wolbitang_data.items(): + print(f"\n{'='*50}") + print(f"{prescription_name} 추가 중...") + + # 1. 처방 기본 정보 추가 + cursor.execute(""" + INSERT INTO prescriptions ( + name, + description, + source, + category, + created_at + ) VALUES (?, ?, ?, ?, ?) + """, ( + prescription_name, + f"{prescription_name} - 월비탕의 단계별 처방", + "임상처방", + "단계별처방", + datetime.now().isoformat() + )) + + prescription_id = cursor.lastrowid + print(f" 처방 ID {prescription_id}로 등록됨") + + # 2. 처방 구성 약재 추가 + ingredients = [] + for herb_name, amount in herbs.items(): + herb_code = herb_code_mapping.get(herb_name) + if not herb_code: + print(f" ⚠️ {herb_name}의 코드를 찾을 수 없습니다.") + continue + + # prescription_ingredients 테이블에 추가 + cursor.execute(""" + INSERT INTO prescription_ingredients ( + prescription_id, + ingredient_code, + amount, + unit + ) VALUES (?, ?, ?, ?) + """, (prescription_id, herb_code, amount, 'g')) + + ingredients.append({ + 'code': herb_code, + 'name': herb_name, + 'amount': amount, + 'unit': 'g' + }) + + print(f" - {herb_name}({herb_code}): {amount}g 추가됨") + + # 3. prescription_details 테이블에 JSON 형태로도 저장 + cursor.execute(""" + INSERT INTO prescription_details ( + prescription_id, + ingredients_json, + total_herbs, + default_packets, + preparation_method + ) VALUES (?, ?, ?, ?, ?) + """, ( + prescription_id, + json.dumps(ingredients, ensure_ascii=False), + len(ingredients), + 20, # 기본 첩수 + "1일 2회, 1회 1포" + )) + + print(f" ✅ {prescription_name} 처방 추가 완료 (총 {len(ingredients)}개 약재)") + + conn.commit() + print(f"\n{'='*50}") + print("✅ 월비탕 1차~4차 처방이 모두 성공적으로 추가되었습니다!") + + # 추가된 처방 확인 + print("\n📊 추가된 처방 목록:") + cursor.execute(""" + SELECT p.id, p.name, pd.total_herbs + FROM prescriptions p + LEFT JOIN prescription_details pd ON p.id = pd.prescription_id + WHERE p.name LIKE '월비탕%' + ORDER BY p.id + """) + + for row in cursor.fetchall(): + print(f" ID {row[0]}: {row[1]} - {row[2]}개 약재") + + except sqlite3.Error as e: + print(f"❌ 데이터베이스 오류: {e}") + conn.rollback() + return False + finally: + conn.close() + + return True + +if __name__ == "__main__": + print("🌿 월비탕 단계별 처방 추가 프로그램") + print("="*50) + + if add_wolbitang_prescriptions(): + print("\n✅ 월비탕 처방 추가 작업이 완료되었습니다.") + else: + print("\n❌ 처방 추가 중 오류가 발생했습니다.") \ No newline at end of file diff --git a/analyze_db_structure.py b/dev_scripts/analyze_db_structure.py similarity index 100% rename from analyze_db_structure.py rename to dev_scripts/analyze_db_structure.py diff --git a/analyze_excel_formats.py b/dev_scripts/analyze_excel_formats.py similarity index 100% rename from analyze_excel_formats.py rename to dev_scripts/analyze_excel_formats.py diff --git a/dev_scripts/analyze_inventory_discrepancy.py b/dev_scripts/analyze_inventory_discrepancy.py new file mode 100644 index 0000000..81629a7 --- /dev/null +++ b/dev_scripts/analyze_inventory_discrepancy.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +재고 자산 금액 불일치 분석 스크립트 +""" + +import sqlite3 +from datetime import datetime +from decimal import Decimal, getcontext + +# Decimal 정밀도 설정 +getcontext().prec = 10 + +def analyze_inventory_discrepancy(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("재고 자산 금액 불일치 분석") + print("=" * 80) + print() + + # 1. 현재 inventory_lots 기준 재고 자산 계산 + print("1. 현재 시스템 재고 자산 계산 (inventory_lots 기준)") + print("-" * 60) + + cursor.execute(""" + SELECT + SUM(quantity_onhand * unit_price_per_g) as total_value, + COUNT(*) as lot_count, + SUM(quantity_onhand) as total_quantity + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + + result = cursor.fetchone() + system_total = result['total_value'] or 0 + + print(f" 총 재고 자산: ₩{system_total:,.0f}") + print(f" 총 LOT 수: {result['lot_count']}개") + print(f" 총 재고량: {result['total_quantity']:,.1f}g") + print() + + # 2. 원본 입고장 데이터 분석 + print("2. 입고장 기준 계산") + print("-" * 60) + + # 전체 입고 금액 + cursor.execute(""" + SELECT + SUM(total_price) as total_purchase, + COUNT(*) as receipt_count, + SUM(quantity_g) as total_quantity + FROM purchase_receipts + """) + + receipts = cursor.fetchone() + total_purchase = receipts['total_purchase'] or 0 + + print(f" 총 입고 금액: ₩{total_purchase:,.0f}") + print(f" 총 입고장 수: {receipts['receipt_count']}건") + print(f" 총 입고량: {receipts['total_quantity']:,.1f}g") + print() + + # 3. 출고 데이터 분석 + print("3. 출고 데이터 분석") + print("-" * 60) + + cursor.execute(""" + SELECT + SUM(pd.quantity * il.unit_price_per_g) as total_dispensed_value, + SUM(pd.quantity) as total_dispensed_quantity, + COUNT(DISTINCT p.prescription_id) as prescription_count + FROM prescription_details pd + JOIN prescriptions p ON pd.prescription_id = p.prescription_id + JOIN inventory_lots il ON pd.lot_id = il.lot_id + WHERE p.status IN ('completed', 'dispensed') + """) + + dispensed = cursor.fetchone() + total_dispensed_value = dispensed['total_dispensed_value'] or 0 + + print(f" 총 출고 금액: ₩{total_dispensed_value:,.0f}") + print(f" 총 출고량: {dispensed['total_dispensed_quantity'] or 0:,.1f}g") + print(f" 총 처방전 수: {dispensed['prescription_count']}건") + print() + + # 4. 재고 보정 데이터 분석 + print("4. 재고 보정 데이터 분석") + print("-" * 60) + + cursor.execute(""" + SELECT + adjustment_type, + SUM(quantity) as total_quantity, + SUM(quantity * unit_price) as total_value, + COUNT(*) as count + FROM stock_adjustments + GROUP BY adjustment_type + """) + + adjustments = cursor.fetchall() + total_adjustment_value = 0 + + for adj in adjustments: + adj_type = adj['adjustment_type'] + value = adj['total_value'] or 0 + + # 보정 타입에 따른 금액 계산 + if adj_type in ['disposal', 'loss', 'decrease']: + total_adjustment_value -= value + print(f" {adj_type}: -₩{value:,.0f} ({adj['count']}건, {adj['total_quantity']:,.1f}g)") + else: + total_adjustment_value += value + print(f" {adj_type}: +₩{value:,.0f} ({adj['count']}건, {adj['total_quantity']:,.1f}g)") + + print(f" 순 보정 금액: ₩{total_adjustment_value:,.0f}") + print() + + # 5. 예상 재고 자산 계산 + print("5. 예상 재고 자산 계산") + print("-" * 60) + + expected_value = total_purchase - total_dispensed_value + total_adjustment_value + + print(f" 입고 금액: ₩{total_purchase:,.0f}") + print(f" - 출고 금액: ₩{total_dispensed_value:,.0f}") + print(f" + 보정 금액: ₩{total_adjustment_value:,.0f}") + print(f" = 예상 재고 자산: ₩{expected_value:,.0f}") + print() + + # 6. 차이 분석 + print("6. 차이 분석") + print("-" * 60) + + discrepancy = system_total - expected_value + discrepancy_pct = (discrepancy / expected_value * 100) if expected_value != 0 else 0 + + print(f" 시스템 재고 자산: ₩{system_total:,.0f}") + print(f" 예상 재고 자산: ₩{expected_value:,.0f}") + print(f" 차이: ₩{discrepancy:,.0f} ({discrepancy_pct:+.2f}%)") + print() + + # 7. 상세 불일치 원인 분석 + print("7. 잠재적 불일치 원인 분석") + print("-" * 60) + + # 7-1. LOT과 입고장 매칭 확인 + cursor.execute(""" + SELECT COUNT(*) as unmatched_lots + FROM inventory_lots il + WHERE il.receipt_id IS NULL AND il.is_depleted = 0 + """) + unmatched = cursor.fetchone() + + if unmatched['unmatched_lots'] > 0: + print(f" ⚠️ 입고장과 매칭되지 않은 LOT: {unmatched['unmatched_lots']}개") + + cursor.execute(""" + SELECT + herb_name, + lot_number, + quantity_onhand, + unit_price_per_g, + quantity_onhand * unit_price_per_g as value + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE il.receipt_id IS NULL AND il.is_depleted = 0 + ORDER BY value DESC + LIMIT 5 + """) + + unmatched_lots = cursor.fetchall() + for lot in unmatched_lots: + print(f" - {lot['herb_name']} (LOT: {lot['lot_number']}): ₩{lot['value']:,.0f}") + + # 7-2. 단가 변동 확인 + cursor.execute(""" + SELECT + h.herb_name, + MIN(il.unit_price_per_g) as min_price, + MAX(il.unit_price_per_g) as max_price, + AVG(il.unit_price_per_g) as avg_price, + MAX(il.unit_price_per_g) - MIN(il.unit_price_per_g) as price_diff + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE il.is_depleted = 0 AND il.quantity_onhand > 0 + GROUP BY h.herb_item_id, h.herb_name + HAVING price_diff > 0 + ORDER BY price_diff DESC + LIMIT 5 + """) + + price_variations = cursor.fetchall() + if price_variations: + print(f"\n ⚠️ 단가 변동이 큰 약재 (동일 약재 다른 단가):") + for item in price_variations: + print(f" - {item['herb_name']}: ₩{item['min_price']:.2f} ~ ₩{item['max_price']:.2f} (차이: ₩{item['price_diff']:.2f})") + + # 7-3. 입고장 없는 출고 확인 + cursor.execute(""" + SELECT COUNT(DISTINCT pd.lot_id) as orphan_dispenses + FROM prescription_details pd + LEFT JOIN inventory_lots il ON pd.lot_id = il.lot_id + WHERE il.lot_id IS NULL + """) + orphan = cursor.fetchone() + + if orphan['orphan_dispenses'] > 0: + print(f"\n ⚠️ LOT 정보 없는 출고: {orphan['orphan_dispenses']}건") + + # 7-4. 음수 재고 확인 + cursor.execute(""" + SELECT COUNT(*) as negative_stock + FROM inventory_lots + WHERE quantity_onhand < 0 + """) + negative = cursor.fetchone() + + if negative['negative_stock'] > 0: + print(f"\n ⚠️ 음수 재고 LOT: {negative['negative_stock']}개") + + # 8. 권장사항 + print("\n8. 권장사항") + print("-" * 60) + + if abs(discrepancy) > 1000: + print(" 🔴 상당한 금액 차이가 발생했습니다. 다음 사항을 확인하세요:") + print(" 1) 모든 입고장이 inventory_lots에 정확히 반영되었는지 확인") + print(" 2) 출고 시 올바른 LOT과 단가가 적용되었는지 확인") + print(" 3) 재고 보정 내역이 정확히 기록되었는지 확인") + print(" 4) 초기 재고 입력 시 단가가 정확했는지 확인") + + if unmatched['unmatched_lots'] > 0: + print(f" 5) 입고장과 매칭되지 않은 {unmatched['unmatched_lots']}개 LOT 확인 필요") + else: + print(" ✅ 재고 자산이 대체로 일치합니다.") + + conn.close() + +if __name__ == "__main__": + analyze_inventory_discrepancy() \ No newline at end of file diff --git a/dev_scripts/analyze_inventory_full.py b/dev_scripts/analyze_inventory_full.py new file mode 100644 index 0000000..9f214aa --- /dev/null +++ b/dev_scripts/analyze_inventory_full.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +재고 자산 금액 불일치 상세 분석 +""" + +import sqlite3 +from datetime import datetime +from decimal import Decimal, getcontext + +# Decimal 정밀도 설정 +getcontext().prec = 10 + +def analyze_inventory_discrepancy(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("재고 자산 금액 불일치 상세 분석") + print("분석 시간:", datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + print("=" * 80) + print() + + # 1. 현재 inventory_lots 기준 재고 자산 + print("1. 현재 시스템 재고 자산 (inventory_lots 테이블)") + print("-" * 60) + + cursor.execute(""" + SELECT + SUM(quantity_onhand * unit_price_per_g) as total_value, + COUNT(*) as lot_count, + SUM(quantity_onhand) as total_quantity, + COUNT(DISTINCT herb_item_id) as herb_count + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + + result = cursor.fetchone() + system_total = result['total_value'] or 0 + + print(f" 💰 총 재고 자산: ₩{system_total:,.0f}") + print(f" 📦 활성 LOT 수: {result['lot_count']}개") + print(f" ⚖️ 총 재고량: {result['total_quantity']:,.1f}g") + print(f" 🌿 약재 종류: {result['herb_count']}종") + print() + + # 2. 입고장 기준 분석 + print("2. 입고장 데이터 분석 (purchase_receipts + purchase_receipt_lines)") + print("-" * 60) + + # 전체 입고 금액 (purchase_receipt_lines 기준) + cursor.execute(""" + SELECT + SUM(prl.line_total) as total_purchase, + COUNT(DISTINCT pr.receipt_id) as receipt_count, + COUNT(*) as line_count, + SUM(prl.quantity_g) as total_quantity + FROM purchase_receipt_lines prl + JOIN purchase_receipts pr ON prl.receipt_id = pr.receipt_id + """) + + receipts = cursor.fetchone() + total_purchase = receipts['total_purchase'] or 0 + + print(f" 📋 총 입고 금액: ₩{total_purchase:,.0f}") + print(f" 📑 입고장 수: {receipts['receipt_count']}건") + print(f" 📝 입고 라인 수: {receipts['line_count']}개") + print(f" ⚖️ 총 입고량: {receipts['total_quantity']:,.1f}g") + + # 입고장별 요약도 확인 + cursor.execute(""" + SELECT + pr.receipt_id, + pr.receipt_no, + pr.receipt_date, + pr.total_amount as receipt_total, + SUM(prl.line_total) as lines_sum + FROM purchase_receipts pr + LEFT JOIN purchase_receipt_lines prl ON pr.receipt_id = prl.receipt_id + GROUP BY pr.receipt_id + ORDER BY pr.receipt_date DESC + LIMIT 5 + """) + + print("\n 최근 입고장 5건:") + recent_receipts = cursor.fetchall() + for r in recent_receipts: + print(f" - {r['receipt_no']} ({r['receipt_date']}): ₩{r['lines_sum']:,.0f}") + + print() + + # 3. inventory_lots와 purchase_receipt_lines 매칭 분석 + print("3. LOT-입고장 매칭 분석") + print("-" * 60) + + # receipt_line_id로 연결된 LOT 분석 + cursor.execute(""" + SELECT + COUNT(*) as total_lots, + SUM(CASE WHEN receipt_line_id IS NOT NULL THEN 1 ELSE 0 END) as matched_lots, + SUM(CASE WHEN receipt_line_id IS NULL THEN 1 ELSE 0 END) as unmatched_lots, + SUM(CASE WHEN receipt_line_id IS NOT NULL THEN quantity_onhand * unit_price_per_g ELSE 0 END) as matched_value, + SUM(CASE WHEN receipt_line_id IS NULL THEN quantity_onhand * unit_price_per_g ELSE 0 END) as unmatched_value + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + + matching = cursor.fetchone() + + print(f" ✅ 입고장과 연결된 LOT: {matching['matched_lots']}개 (₩{matching['matched_value']:,.0f})") + print(f" ❌ 입고장 없는 LOT: {matching['unmatched_lots']}개 (₩{matching['unmatched_value']:,.0f})") + + if matching['unmatched_lots'] > 0: + print("\n 입고장 없는 LOT 상세:") + cursor.execute(""" + SELECT + h.herb_name, + il.lot_number, + il.quantity_onhand, + il.unit_price_per_g, + il.quantity_onhand * il.unit_price_per_g as value, + il.received_date + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE il.receipt_line_id IS NULL + AND il.is_depleted = 0 + AND il.quantity_onhand > 0 + ORDER BY value DESC + LIMIT 5 + """) + + unmatched_lots = cursor.fetchall() + for lot in unmatched_lots: + print(f" - {lot['herb_name']} (LOT: {lot['lot_number']})") + print(f" 재고: {lot['quantity_onhand']:,.0f}g, 단가: ₩{lot['unit_price_per_g']:.2f}, 금액: ₩{lot['value']:,.0f}") + + print() + + # 4. 입고장 라인과 LOT 비교 + print("4. 입고장 라인별 LOT 생성 확인") + print("-" * 60) + + cursor.execute(""" + SELECT + COUNT(*) as total_lines, + SUM(CASE WHEN il.lot_id IS NOT NULL THEN 1 ELSE 0 END) as lines_with_lot, + SUM(CASE WHEN il.lot_id IS NULL THEN 1 ELSE 0 END) as lines_without_lot + FROM purchase_receipt_lines prl + LEFT JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + """) + + line_matching = cursor.fetchone() + + print(f" 📝 전체 입고 라인: {line_matching['total_lines']}개") + print(f" ✅ LOT 생성된 라인: {line_matching['lines_with_lot']}개") + print(f" ❌ LOT 없는 라인: {line_matching['lines_without_lot']}개") + + if line_matching['lines_without_lot'] > 0: + print("\n ⚠️ LOT이 생성되지 않은 입고 라인이 있습니다!") + cursor.execute(""" + SELECT + pr.receipt_no, + pr.receipt_date, + h.herb_name, + prl.quantity_g, + prl.line_total + FROM purchase_receipt_lines prl + JOIN purchase_receipts pr ON prl.receipt_id = pr.receipt_id + JOIN herb_items h ON prl.herb_item_id = h.herb_item_id + LEFT JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + WHERE il.lot_id IS NULL + ORDER BY prl.line_total DESC + LIMIT 5 + """) + + missing_lots = cursor.fetchall() + for line in missing_lots: + print(f" - {line['receipt_no']} ({line['receipt_date']}): {line['herb_name']}") + print(f" 수량: {line['quantity_g']:,.0f}g, 금액: ₩{line['line_total']:,.0f}") + + print() + + # 5. 금액 차이 계산 + print("5. 재고 자산 차이 분석") + print("-" * 60) + + # 입고장 라인별로 생성된 LOT의 현재 재고 가치 합계 + cursor.execute(""" + SELECT + SUM(il.quantity_onhand * il.unit_price_per_g) as current_lot_value, + SUM(prl.line_total) as original_purchase_value + FROM purchase_receipt_lines prl + JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + WHERE il.is_depleted = 0 AND il.quantity_onhand > 0 + """) + + value_comparison = cursor.fetchone() + + if value_comparison['current_lot_value']: + print(f" 💰 현재 LOT 재고 가치: ₩{value_comparison['current_lot_value']:,.0f}") + print(f" 📋 원본 입고 금액: ₩{value_comparison['original_purchase_value']:,.0f}") + print(f" 📊 차이: ₩{(value_comparison['current_lot_value'] - value_comparison['original_purchase_value']):,.0f}") + + print() + + # 6. 출고 내역 확인 + print("6. 출고 및 소비 내역") + print("-" * 60) + + # 처방전을 통한 출고가 있는지 확인 + cursor.execute(""" + SELECT name FROM sqlite_master + WHERE type='table' AND name IN ('prescriptions', 'prescription_details') + """) + prescription_tables = cursor.fetchall() + + if len(prescription_tables) == 2: + cursor.execute(""" + SELECT + SUM(pd.quantity * il.unit_price_per_g) as dispensed_value, + SUM(pd.quantity) as dispensed_quantity, + COUNT(DISTINCT p.prescription_id) as prescription_count + FROM prescription_details pd + JOIN prescriptions p ON pd.prescription_id = p.prescription_id + JOIN inventory_lots il ON pd.lot_id = il.lot_id + WHERE p.status IN ('completed', 'dispensed') + """) + + dispensed = cursor.fetchone() + if dispensed and dispensed['dispensed_value']: + print(f" 💊 처방 출고 금액: ₩{dispensed['dispensed_value']:,.0f}") + print(f" ⚖️ 처방 출고량: {dispensed['dispensed_quantity']:,.1f}g") + print(f" 📋 처방전 수: {dispensed['prescription_count']}건") + else: + print(" 처방전 테이블이 없습니다.") + + # 복합제 소비 확인 + cursor.execute(""" + SELECT + SUM(cc.quantity_used * il.unit_price_per_g) as compound_value, + SUM(cc.quantity_used) as compound_quantity, + COUNT(DISTINCT cc.compound_id) as compound_count + FROM compound_consumptions cc + JOIN inventory_lots il ON cc.lot_id = il.lot_id + """) + + compounds = cursor.fetchone() + if compounds and compounds['compound_value']: + print(f" 🏭 복합제 소비 금액: ₩{compounds['compound_value']:,.0f}") + print(f" ⚖️ 복합제 소비량: {compounds['compound_quantity']:,.1f}g") + print(f" 📦 복합제 수: {compounds['compound_count']}개") + + print() + + # 7. 재고 보정 내역 + print("7. 재고 보정 내역") + print("-" * 60) + + cursor.execute(""" + SELECT + adjustment_type, + SUM(quantity) as total_quantity, + SUM(quantity * unit_price) as total_value, + COUNT(*) as count + FROM stock_adjustments + GROUP BY adjustment_type + """) + + adjustments = cursor.fetchall() + total_adjustment = 0 + + for adj in adjustments: + adj_type = adj['adjustment_type'] + value = adj['total_value'] or 0 + + if adj_type in ['disposal', 'loss', 'decrease']: + total_adjustment -= value + print(f" ➖ {adj_type}: -₩{value:,.0f} ({adj['count']}건, {adj['total_quantity']:,.1f}g)") + else: + total_adjustment += value + print(f" ➕ {adj_type}: +₩{value:,.0f} ({adj['count']}건, {adj['total_quantity']:,.1f}g)") + + print(f"\n 📊 순 보정 금액: ₩{total_adjustment:,.0f}") + print() + + # 8. 최종 분석 결과 + print("8. 최종 분석 결과") + print("=" * 60) + + print(f"\n 💰 화면 표시 재고 자산: ₩5,875,708") + print(f" 📊 실제 계산 재고 자산: ₩{system_total:,.0f}") + print(f" ❗ 차이: ₩{5875708 - system_total:,.0f}") + + print("\n 🔍 불일치 원인:") + + if matching['unmatched_lots'] > 0: + print(f" 1) 입고장과 연결되지 않은 LOT {matching['unmatched_lots']}개 (₩{matching['unmatched_value']:,.0f})") + + if line_matching['lines_without_lot'] > 0: + print(f" 2) LOT이 생성되지 않은 입고 라인 {line_matching['lines_without_lot']}개") + + print(f" 3) 화면의 ₩5,875,708과 실제 DB의 ₩{system_total:,.0f} 차이") + + # 화면에 표시되는 금액이 어디서 오는지 추가 확인 + print("\n 💡 추가 확인 필요사항:") + print(" - 프론트엔드에서 재고 자산을 계산하는 로직 확인") + print(" - 캐시된 데이터나 별도 계산 로직이 있는지 확인") + print(" - inventory_lots_v2 테이블 데이터와 비교 필요") + + conn.close() + +if __name__ == "__main__": + analyze_inventory_discrepancy() \ No newline at end of file diff --git a/dev_scripts/analyze_price_difference.py b/dev_scripts/analyze_price_difference.py new file mode 100644 index 0000000..3499d46 --- /dev/null +++ b/dev_scripts/analyze_price_difference.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +입고 단가와 LOT 단가 차이 분석 +""" + +import sqlite3 + +def analyze_price_difference(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("입고 단가와 LOT 단가 차이 상세 분석") + print("=" * 80) + print() + + # 1. 입고 라인과 LOT의 단가 차이 분석 + print("1. 입고 라인 vs LOT 단가 비교") + print("-" * 60) + + cursor.execute(""" + SELECT + h.herb_name, + prl.line_id, + prl.quantity_g as purchase_qty, + prl.unit_price_per_g as purchase_price, + prl.line_total as purchase_total, + il.quantity_received as lot_received_qty, + il.quantity_onhand as lot_current_qty, + il.unit_price_per_g as lot_price, + il.quantity_received * il.unit_price_per_g as lot_original_value, + il.quantity_onhand * il.unit_price_per_g as lot_current_value, + ABS(prl.unit_price_per_g - il.unit_price_per_g) as price_diff, + prl.line_total - (il.quantity_received * il.unit_price_per_g) as value_diff + FROM purchase_receipt_lines prl + JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + JOIN herb_items h ON prl.herb_item_id = h.herb_item_id + WHERE ABS(prl.unit_price_per_g - il.unit_price_per_g) > 0.01 + OR ABS(prl.quantity_g - il.quantity_received) > 0.01 + ORDER BY ABS(value_diff) DESC + """) + + diffs = cursor.fetchall() + + if diffs: + print(f" ⚠️ 단가 또는 수량이 다른 항목: {len(diffs)}개\n") + + total_value_diff = 0 + for i, diff in enumerate(diffs[:10], 1): + print(f" {i}. {diff['herb_name']}") + print(f" 입고: {diff['purchase_qty']:,.0f}g × ₩{diff['purchase_price']:.2f} = ₩{diff['purchase_total']:,.0f}") + print(f" LOT: {diff['lot_received_qty']:,.0f}g × ₩{diff['lot_price']:.2f} = ₩{diff['lot_original_value']:,.0f}") + print(f" 차이: ₩{diff['value_diff']:,.0f}") + total_value_diff += diff['value_diff'] + print() + + cursor.execute(""" + SELECT SUM(prl.line_total - (il.quantity_received * il.unit_price_per_g)) as total_diff + FROM purchase_receipt_lines prl + JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + """) + total_diff = cursor.fetchone()['total_diff'] or 0 + + print(f" 총 차이 금액: ₩{total_diff:,.0f}") + else: + print(" ✅ 모든 입고 라인과 LOT의 단가/수량이 일치합니다.") + + # 2. 입고 총액과 LOT 생성 총액 비교 + print("\n2. 입고 총액 vs LOT 생성 총액") + print("-" * 60) + + cursor.execute(""" + SELECT + SUM(prl.line_total) as purchase_total, + SUM(il.quantity_received * il.unit_price_per_g) as lot_creation_total + FROM purchase_receipt_lines prl + JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + """) + + totals = cursor.fetchone() + + print(f" 입고장 총액: ₩{totals['purchase_total']:,.0f}") + print(f" LOT 생성 총액: ₩{totals['lot_creation_total']:,.0f}") + print(f" 차이: ₩{totals['purchase_total'] - totals['lot_creation_total']:,.0f}") + + # 3. 소비로 인한 차이 분석 + print("\n3. 소비 내역 상세 분석") + print("-" * 60) + + # 복합제 소비 상세 + cursor.execute(""" + SELECT + c.compound_name, + h.herb_name, + cc.quantity_used, + il.unit_price_per_g, + cc.quantity_used * il.unit_price_per_g as consumption_value, + cc.consumption_date + FROM compound_consumptions cc + JOIN inventory_lots il ON cc.lot_id = il.lot_id + JOIN compounds c ON cc.compound_id = c.compound_id + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + ORDER BY consumption_value DESC + LIMIT 10 + """) + + consumptions = cursor.fetchall() + + print(" 복합제 소비 내역 (상위 10개):") + total_consumption = 0 + for cons in consumptions: + print(f" - {cons['compound_name']} - {cons['herb_name']}") + print(f" {cons['quantity_used']:,.0f}g × ₩{cons['unit_price_per_g']:.2f} = ₩{cons['consumption_value']:,.0f}") + total_consumption += cons['consumption_value'] + + cursor.execute(""" + SELECT SUM(cc.quantity_used * il.unit_price_per_g) as total + FROM compound_consumptions cc + JOIN inventory_lots il ON cc.lot_id = il.lot_id + """) + total_consumed = cursor.fetchone()['total'] or 0 + + print(f"\n 총 소비 금액: ₩{total_consumed:,.0f}") + + # 4. 재고 자산 흐름 요약 + print("\n4. 재고 자산 흐름 요약") + print("=" * 60) + + # 입고장 기준 + cursor.execute("SELECT SUM(line_total) as total FROM purchase_receipt_lines") + receipt_total = cursor.fetchone()['total'] or 0 + + # LOT 생성 기준 + cursor.execute(""" + SELECT SUM(quantity_received * unit_price_per_g) as total + FROM inventory_lots + WHERE receipt_line_id IS NOT NULL + """) + lot_creation = cursor.fetchone()['total'] or 0 + + # 현재 LOT 재고 + cursor.execute(""" + SELECT SUM(quantity_onhand * unit_price_per_g) as total + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + current_inventory = cursor.fetchone()['total'] or 0 + + print(f" 1) 입고장 총액: ₩{receipt_total:,.0f}") + print(f" 2) LOT 생성 총액: ₩{lot_creation:,.0f}") + print(f" 차이 (1-2): ₩{receipt_total - lot_creation:,.0f}") + print() + print(f" 3) 복합제 소비: ₩{total_consumed:,.0f}") + print(f" 4) 현재 재고: ₩{current_inventory:,.0f}") + print() + print(f" 예상 재고 (2-3): ₩{lot_creation - total_consumed:,.0f}") + print(f" 실제 재고: ₩{current_inventory:,.0f}") + print(f" 차이: ₩{current_inventory - (lot_creation - total_consumed):,.0f}") + + # 5. 차이 원인 설명 + print("\n5. 차이 원인 분석") + print("-" * 60) + + price_diff = receipt_total - lot_creation + if abs(price_diff) > 1000: + print(f"\n 💡 입고장과 LOT 생성 시 ₩{abs(price_diff):,.0f} 차이가 있습니다.") + print(" 가능한 원인:") + print(" - VAT 포함/제외 계산 차이") + print(" - 단가 반올림 차이") + print(" - 입고 시점의 환율 적용 차이") + + consumption_diff = current_inventory - (lot_creation - total_consumed) + if abs(consumption_diff) > 1000: + print(f"\n 💡 예상 재고와 실제 재고 간 ₩{abs(consumption_diff):,.0f} 차이가 있습니다.") + print(" 가능한 원인:") + print(" - 재고 보정 내역") + print(" - 소비 시 반올림 오차 누적") + print(" - 초기 데이터 입력 오류") + + conn.close() + +if __name__ == "__main__": + analyze_price_difference() \ No newline at end of file diff --git a/analyze_product_code.py b/dev_scripts/analyze_product_code.py similarity index 100% rename from analyze_product_code.py rename to dev_scripts/analyze_product_code.py diff --git a/analyze_product_deep.py b/dev_scripts/analyze_product_deep.py similarity index 100% rename from analyze_product_deep.py rename to dev_scripts/analyze_product_deep.py diff --git a/check_and_create_efficacy_tags.py b/dev_scripts/check_and_create_efficacy_tags.py similarity index 100% rename from check_and_create_efficacy_tags.py rename to dev_scripts/check_and_create_efficacy_tags.py diff --git a/check_custom_prescription.py b/dev_scripts/check_custom_prescription.py similarity index 100% rename from check_custom_prescription.py rename to dev_scripts/check_custom_prescription.py diff --git a/check_formula_columns.py b/dev_scripts/check_formula_columns.py similarity index 100% rename from check_formula_columns.py rename to dev_scripts/check_formula_columns.py diff --git a/dev_scripts/check_herb_data.py b/dev_scripts/check_herb_data.py new file mode 100644 index 0000000..ad00848 --- /dev/null +++ b/dev_scripts/check_herb_data.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""약재 데이터 확인""" + +import sqlite3 + +conn = sqlite3.connect('kdrug.db') +cur = conn.cursor() + +# 확장 정보가 있는 약재 확인 +cur.execute(""" + SELECT COUNT(*) FROM herb_master_extended + WHERE nature IS NOT NULL OR taste IS NOT NULL +""") +extended_count = cur.fetchone()[0] +print(f"확장 정보가 있는 약재: {extended_count}개") + +# 효능 태그가 있는 약재 확인 +cur.execute("SELECT COUNT(DISTINCT ingredient_code) FROM herb_item_tags") +tagged_count = cur.fetchone()[0] +print(f"효능 태그가 있는 약재: {tagged_count}개") + +# 구체적인 데이터 확인 +cur.execute(""" + SELECT hme.ingredient_code, hme.herb_name, hme.nature, hme.taste + FROM herb_master_extended hme + WHERE hme.nature IS NOT NULL OR hme.taste IS NOT NULL + LIMIT 5 +""") +print("\n확장 정보 샘플:") +for row in cur.fetchall(): + print(f" - {row[1]} ({row[0]}): {row[2]}/{row[3]}") + +# herb_item_tags 데이터 확인 +cur.execute(""" + SELECT hit.ingredient_code, het.name, COUNT(*) as count + FROM herb_item_tags hit + JOIN herb_efficacy_tags het ON hit.tag_id = het.tag_id + GROUP BY hit.ingredient_code + LIMIT 5 +""") +print("\n효능 태그 샘플:") +for row in cur.fetchall(): + print(f" - {row[0]}: {row[2]}개 태그") + +conn.close() \ No newline at end of file diff --git a/dev_scripts/check_lot_creation_methods.py b/dev_scripts/check_lot_creation_methods.py new file mode 100644 index 0000000..27cc985 --- /dev/null +++ b/dev_scripts/check_lot_creation_methods.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +LOT 생성 방법 분석 - 입고장 연결 vs 독립 생성 +""" + +import sqlite3 + +def check_lot_creation_methods(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("📦 LOT 생성 방법 분석") + print("=" * 80) + print() + + # 1. 전체 LOT 현황 + print("1. 전체 LOT 현황") + print("-" * 60) + + cursor.execute(""" + SELECT + COUNT(*) as total_lots, + SUM(CASE WHEN receipt_line_id IS NOT NULL THEN 1 ELSE 0 END) as with_receipt, + SUM(CASE WHEN receipt_line_id IS NULL THEN 1 ELSE 0 END) as without_receipt, + SUM(CASE WHEN is_depleted = 0 THEN 1 ELSE 0 END) as active_lots + FROM inventory_lots + """) + + stats = cursor.fetchone() + + print(f" 전체 LOT 수: {stats['total_lots']}개") + print(f" ✅ 입고장 연결: {stats['with_receipt']}개") + print(f" ❌ 입고장 없음: {stats['without_receipt']}개") + print(f" 활성 LOT: {stats['active_lots']}개") + + # 2. 입고장 없는 LOT 상세 + if stats['without_receipt'] > 0: + print("\n2. 입고장 없이 생성된 LOT 상세") + print("-" * 60) + + cursor.execute(""" + SELECT + il.lot_id, + h.herb_name, + il.lot_number, + il.quantity_received, + il.quantity_onhand, + il.unit_price_per_g, + il.quantity_onhand * il.unit_price_per_g as value, + il.received_date, + il.created_at + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE il.receipt_line_id IS NULL + ORDER BY il.created_at DESC + """) + + no_receipt_lots = cursor.fetchall() + + for lot in no_receipt_lots: + print(f"\n LOT {lot['lot_id']}: {lot['herb_name']}") + print(f" LOT 번호: {lot['lot_number'] or 'None'}") + print(f" 수량: {lot['quantity_received']:,.0f}g → {lot['quantity_onhand']:,.0f}g") + print(f" 단가: ₩{lot['unit_price_per_g']:.2f}") + print(f" 재고 가치: ₩{lot['value']:,.0f}") + print(f" 입고일: {lot['received_date']}") + print(f" 생성일: {lot['created_at']}") + + # 금액 합계 + cursor.execute(""" + SELECT + SUM(quantity_onhand * unit_price_per_g) as total_value, + SUM(quantity_onhand) as total_qty + FROM inventory_lots + WHERE receipt_line_id IS NULL + AND is_depleted = 0 + AND quantity_onhand > 0 + """) + + no_receipt_total = cursor.fetchone() + + if no_receipt_total['total_value']: + print(f"\n 📊 입고장 없는 LOT 합계:") + print(f" 총 재고량: {no_receipt_total['total_qty']:,.0f}g") + print(f" 총 재고 가치: ₩{no_receipt_total['total_value']:,.0f}") + + # 3. LOT 생성 방법별 재고 자산 + print("\n3. LOT 생성 방법별 재고 자산") + print("-" * 60) + + cursor.execute(""" + SELECT + CASE + WHEN receipt_line_id IS NOT NULL THEN '입고장 연결' + ELSE '직접 생성' + END as creation_type, + COUNT(*) as lot_count, + SUM(quantity_onhand) as total_qty, + SUM(quantity_onhand * unit_price_per_g) as total_value + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + GROUP BY creation_type + """) + + by_type = cursor.fetchall() + + total_value = 0 + for row in by_type: + print(f"\n {row['creation_type']}:") + print(f" LOT 수: {row['lot_count']}개") + print(f" 재고량: {row['total_qty']:,.0f}g") + print(f" 재고 가치: ₩{row['total_value']:,.0f}") + total_value += row['total_value'] + + print(f"\n 📊 전체 재고 자산: ₩{total_value:,.0f}") + + # 4. 시스템 설계 분석 + print("\n4. 시스템 설계 분석") + print("=" * 60) + + print("\n 💡 현재 시스템은 두 가지 방법으로 LOT 생성 가능:") + print(" 1) 입고장 등록 시 자동 생성 (receipt_line_id 연결)") + print(" 2) 재고 직접 입력 (receipt_line_id = NULL)") + print() + print(" 📌 재고 자산 계산 로직:") + print(" - 입고장 연결 여부와 관계없이") + print(" - 모든 활성 LOT의 (수량 × 단가) 합계") + print() + + if stats['without_receipt'] > 0: + print(" ⚠️ 주의사항:") + print(" - 입고장 없는 LOT이 존재합니다") + print(" - 초기 재고 입력이나 재고 조정으로 생성된 것으로 추정") + print(" - 회계 추적을 위해서는 입고장 연결 권장") + + conn.close() + +if __name__ == "__main__": + check_lot_creation_methods() \ No newline at end of file diff --git a/dev_scripts/check_missing_lots.py b/dev_scripts/check_missing_lots.py new file mode 100644 index 0000000..6da25a4 --- /dev/null +++ b/dev_scripts/check_missing_lots.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +LOT이 생성되지 않은 입고 라인 확인 +""" + +import sqlite3 + +def check_missing_lots(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("LOT이 생성되지 않은 입고 라인 분석") + print("=" * 80) + print() + + # 1. 전체 입고 라인과 LOT 매칭 상태 + print("1. 입고 라인 - LOT 매칭 현황") + print("-" * 60) + + cursor.execute(""" + SELECT + COUNT(*) as total_lines, + SUM(CASE WHEN il.lot_id IS NOT NULL THEN 1 ELSE 0 END) as lines_with_lot, + SUM(CASE WHEN il.lot_id IS NULL THEN 1 ELSE 0 END) as lines_without_lot, + SUM(prl.line_total) as total_purchase_amount, + SUM(CASE WHEN il.lot_id IS NOT NULL THEN prl.line_total ELSE 0 END) as amount_with_lot, + SUM(CASE WHEN il.lot_id IS NULL THEN prl.line_total ELSE 0 END) as amount_without_lot + FROM purchase_receipt_lines prl + LEFT JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + """) + + result = cursor.fetchone() + + print(f" 총 입고 라인: {result['total_lines']}개") + print(f" ✅ LOT 생성됨: {result['lines_with_lot']}개 (₩{result['amount_with_lot']:,.0f})") + print(f" ❌ LOT 없음: {result['lines_without_lot']}개 (₩{result['amount_without_lot']:,.0f})") + print() + print(f" 총 입고 금액: ₩{result['total_purchase_amount']:,.0f}") + print(f" LOT 없는 금액: ₩{result['amount_without_lot']:,.0f}") + + if result['amount_without_lot'] > 0: + print(f"\n ⚠️ LOT이 생성되지 않은 입고 금액이 ₩{result['amount_without_lot']:,.0f} 있습니다!") + print(" 이것이 DB 재고와 예상 재고 차이(₩55,500)의 원인일 가능성이 높습니다.") + + # 2. LOT이 없는 입고 라인 상세 + if result['lines_without_lot'] > 0: + print("\n2. LOT이 생성되지 않은 입고 라인 상세") + print("-" * 60) + + cursor.execute(""" + SELECT + pr.receipt_no, + pr.receipt_date, + h.herb_name, + prl.quantity_g, + prl.unit_price_per_g, + prl.line_total, + prl.lot_number, + prl.line_id + FROM purchase_receipt_lines prl + JOIN purchase_receipts pr ON prl.receipt_id = pr.receipt_id + JOIN herb_items h ON prl.herb_item_id = h.herb_item_id + LEFT JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + WHERE il.lot_id IS NULL + ORDER BY prl.line_total DESC + """) + + missing_lots = cursor.fetchall() + + total_missing_amount = 0 + print("\n LOT이 생성되지 않은 입고 라인:") + for i, line in enumerate(missing_lots, 1): + print(f"\n {i}. {line['herb_name']}") + print(f" 입고장: {line['receipt_no']} ({line['receipt_date']})") + print(f" 수량: {line['quantity_g']:,.0f}g") + print(f" 단가: ₩{line['unit_price_per_g']:.2f}/g") + print(f" 금액: ₩{line['line_total']:,.0f}") + print(f" LOT번호: {line['lot_number'] or 'None'}") + print(f" Line ID: {line['line_id']}") + total_missing_amount += line['line_total'] + + print(f"\n 총 누락 금액: ₩{total_missing_amount:,.0f}") + + # 3. 반대로 입고 라인 없는 LOT 확인 + print("\n3. 입고 라인과 연결되지 않은 LOT") + print("-" * 60) + + cursor.execute(""" + SELECT + COUNT(*) as orphan_lots, + SUM(quantity_onhand * unit_price_per_g) as orphan_value, + SUM(quantity_onhand) as orphan_quantity + FROM inventory_lots + WHERE receipt_line_id IS NULL + AND is_depleted = 0 + AND quantity_onhand > 0 + """) + + orphans = cursor.fetchone() + + if orphans['orphan_lots'] > 0: + print(f" 입고 라인 없는 LOT: {orphans['orphan_lots']}개") + print(f" 해당 재고 가치: ₩{orphans['orphan_value']:,.0f}") + print(f" 해당 재고량: {orphans['orphan_quantity']:,.0f}g") + + cursor.execute(""" + SELECT + h.herb_name, + il.lot_number, + il.quantity_onhand, + il.unit_price_per_g, + il.quantity_onhand * il.unit_price_per_g as value, + il.received_date + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE il.receipt_line_id IS NULL + AND il.is_depleted = 0 + AND il.quantity_onhand > 0 + ORDER BY value DESC + LIMIT 5 + """) + + orphan_lots = cursor.fetchall() + if orphan_lots: + print("\n 상위 5개 입고 라인 없는 LOT:") + for lot in orphan_lots: + print(f" - {lot['herb_name']} (LOT: {lot['lot_number']})") + print(f" 재고: {lot['quantity_onhand']:,.0f}g, 금액: ₩{lot['value']:,.0f}") + else: + print(" ✅ 모든 LOT이 입고 라인과 연결되어 있습니다.") + + # 4. 금액 차이 분석 + print("\n4. 금액 차이 최종 분석") + print("=" * 60) + + # 현재 DB 재고 + cursor.execute(""" + SELECT SUM(quantity_onhand * unit_price_per_g) as total + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + db_total = cursor.fetchone()['total'] or 0 + + # 총 입고 - 소비 + cursor.execute("SELECT SUM(line_total) as total FROM purchase_receipt_lines") + total_in = cursor.fetchone()['total'] or 0 + + cursor.execute(""" + SELECT SUM(cc.quantity_used * il.unit_price_per_g) as total + FROM compound_consumptions cc + JOIN inventory_lots il ON cc.lot_id = il.lot_id + """) + total_out = cursor.fetchone()['total'] or 0 + + expected = total_in - total_out + + print(f" DB 재고 자산: ₩{db_total:,.0f}") + print(f" 예상 재고 (입고-소비): ₩{expected:,.0f}") + print(f" 차이: ₩{expected - db_total:,.0f}") + print() + + if result['amount_without_lot'] > 0: + print(f" 💡 LOT 없는 입고 금액: ₩{result['amount_without_lot']:,.0f}") + adjusted_expected = (total_in - result['amount_without_lot']) - total_out + print(f" 📊 조정된 예상 재고: ₩{adjusted_expected:,.0f}") + print(f" 조정 후 차이: ₩{adjusted_expected - db_total:,.0f}") + + if abs(adjusted_expected - db_total) < 1000: + print("\n ✅ LOT이 생성되지 않은 입고 라인을 제외하면 차이가 거의 없습니다!") + print(" 이것이 차이의 주요 원인입니다.") + + conn.close() + +if __name__ == "__main__": + check_missing_lots() \ No newline at end of file diff --git a/dev_scripts/check_purchase_structure.py b/dev_scripts/check_purchase_structure.py new file mode 100644 index 0000000..61dd94e --- /dev/null +++ b/dev_scripts/check_purchase_structure.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import sqlite3 + +conn = sqlite3.connect('database/kdrug.db') +cursor = conn.cursor() + +print("=== purchase_receipts 테이블 구조 ===") +cursor.execute("PRAGMA table_info(purchase_receipts)") +columns = cursor.fetchall() +for col in columns: + print(f" {col[1]}: {col[2]}") + +print("\n=== purchase_receipt_lines 테이블 구조 ===") +cursor.execute("PRAGMA table_info(purchase_receipt_lines)") +columns = cursor.fetchall() +for col in columns: + print(f" {col[1]}: {col[2]}") + +print("\n=== 입고장 데이터 샘플 ===") +cursor.execute(""" + SELECT pr.receipt_id, pr.receipt_number, pr.receipt_date, + COUNT(prl.line_id) as line_count, + SUM(prl.quantity_g) as total_quantity, + SUM(prl.total_price) as total_amount + FROM purchase_receipts pr + LEFT JOIN purchase_receipt_lines prl ON pr.receipt_id = prl.receipt_id + GROUP BY pr.receipt_id + LIMIT 5 +""") +rows = cursor.fetchall() +for row in rows: + print(f" 입고장 {row[0]}: {row[1]} ({row[2]})") + print(f" - 항목수: {row[3]}개, 총량: {row[4]}g, 총액: ₩{row[5]:,.0f}") + +print("\n=== inventory_lots의 receipt_line_id 연결 확인 ===") +cursor.execute(""" + SELECT + COUNT(*) as total_lots, + SUM(CASE WHEN receipt_line_id IS NOT NULL THEN 1 ELSE 0 END) as matched_lots, + SUM(CASE WHEN receipt_line_id IS NULL THEN 1 ELSE 0 END) as unmatched_lots + FROM inventory_lots + WHERE is_depleted = 0 +""") +result = cursor.fetchone() +print(f" 전체 LOT: {result[0]}개") +print(f" 입고장 연결된 LOT: {result[1]}개") +print(f" 입고장 연결 안된 LOT: {result[2]}개") + +conn.close() \ No newline at end of file diff --git a/dev_scripts/check_purchase_tables.py b/dev_scripts/check_purchase_tables.py new file mode 100644 index 0000000..8f2c0db --- /dev/null +++ b/dev_scripts/check_purchase_tables.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import sqlite3 + +conn = sqlite3.connect('database/kdrug.db') +cursor = conn.cursor() + +# 테이블 목록 확인 +cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") +tables = cursor.fetchall() + +print("=== 전체 테이블 목록 ===") +for table in tables: + print(f" - {table[0]}") + +print("\n=== inventory_lots 테이블 구조 ===") +cursor.execute("PRAGMA table_info(inventory_lots)") +columns = cursor.fetchall() +for col in columns: + print(f" {col[1]}: {col[2]}") + +print("\n=== inventory_lots 샘플 데이터 ===") +cursor.execute(""" + SELECT lot_id, lot_number, herb_item_id, quantity_onhand, + unit_price_per_g, received_date, receipt_id + FROM inventory_lots + WHERE is_depleted = 0 + LIMIT 5 +""") +rows = cursor.fetchall() +for row in rows: + print(f" LOT {row[0]}: {row[1]}, 재고:{row[3]}g, 단가:₩{row[4]}, 입고일:{row[5]}, receipt_id:{row[6]}") + +conn.close() \ No newline at end of file diff --git a/check_samsoeun_ingredients.py b/dev_scripts/check_samsoeun_ingredients.py similarity index 100% rename from check_samsoeun_ingredients.py rename to dev_scripts/check_samsoeun_ingredients.py diff --git a/check_sipjeondaebotang.py b/dev_scripts/check_sipjeondaebotang.py similarity index 100% rename from check_sipjeondaebotang.py rename to dev_scripts/check_sipjeondaebotang.py diff --git a/check_ssanghwatang.py b/dev_scripts/check_ssanghwatang.py similarity index 100% rename from check_ssanghwatang.py rename to dev_scripts/check_ssanghwatang.py diff --git a/dev_scripts/check_tables.py b/dev_scripts/check_tables.py new file mode 100644 index 0000000..15aff88 --- /dev/null +++ b/dev_scripts/check_tables.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +import sqlite3 + +conn = sqlite3.connect('database/kdrug.db') +cur = conn.cursor() + +# herb_item_tags 테이블 구조 확인 +cur.execute("PRAGMA table_info(herb_item_tags)") +print("herb_item_tags 테이블 구조:") +for row in cur.fetchall(): + print(f" {row}") + +# 실제 테이블 목록 확인 +cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'herb%' ORDER BY name") +print("\n약재 관련 테이블:") +for row in cur.fetchall(): + print(f" - {row[0]}") + +conn.close() \ No newline at end of file diff --git a/check_totals.py b/dev_scripts/check_totals.py similarity index 100% rename from check_totals.py rename to dev_scripts/check_totals.py diff --git a/check_wolbitang_ingredients.py b/dev_scripts/check_wolbitang_ingredients.py similarity index 100% rename from check_wolbitang_ingredients.py rename to dev_scripts/check_wolbitang_ingredients.py diff --git a/dev_scripts/debug_api_calculation.py b/dev_scripts/debug_api_calculation.py new file mode 100644 index 0000000..389b746 --- /dev/null +++ b/dev_scripts/debug_api_calculation.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +API 재고 계산 디버깅 +""" + +import sqlite3 + +def debug_api_calculation(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("API 재고 계산 디버깅") + print("=" * 80) + print() + + # API와 동일한 쿼리 실행 + cursor.execute(""" + SELECT + h.herb_item_id, + h.insurance_code, + h.herb_name, + COALESCE(SUM(il.quantity_onhand), 0) as total_quantity, + COUNT(DISTINCT il.lot_id) as lot_count, + COUNT(DISTINCT il.origin_country) as origin_count, + AVG(il.unit_price_per_g) as avg_price, + MIN(il.unit_price_per_g) as min_price, + MAX(il.unit_price_per_g) as max_price, + COALESCE(SUM(il.quantity_onhand * il.unit_price_per_g), 0) as total_value + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0 + GROUP BY h.herb_item_id, h.insurance_code, h.herb_name + HAVING total_quantity > 0 + ORDER BY total_value DESC + """) + + items = cursor.fetchall() + + print("상위 10개 약재별 재고 가치:") + print("-" * 60) + + total_api_value = 0 + for i, item in enumerate(items[:10], 1): + value = item['total_value'] + total_api_value += value + print(f"{i:2}. {item['herb_name']:15} 재고:{item['total_quantity']:8.0f}g 금액:₩{value:10,.0f}") + + # 전체 합계 계산 + total_api_value = sum(item['total_value'] for item in items) + + print() + print(f"전체 약재 수: {len(items)}개") + print(f"API 계산 총액: ₩{total_api_value:,.0f}") + print() + + # 직접 inventory_lots에서 계산 + cursor.execute(""" + SELECT + SUM(quantity_onhand * unit_price_per_g) as direct_total + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + direct_total = cursor.fetchone()['direct_total'] or 0 + + print(f"직접 계산 총액: ₩{direct_total:,.0f}") + print(f"차이: ₩{total_api_value - direct_total:,.0f}") + print() + + # 차이 원인 분석 + if abs(total_api_value - direct_total) > 1: + print("차이 원인 분석:") + print("-" * 40) + + # 중복 LOT 확인 + cursor.execute(""" + SELECT + h.herb_name, + COUNT(*) as lot_count, + SUM(il.quantity_onhand * il.unit_price_per_g) as total_value + FROM herb_items h + JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id + WHERE il.is_depleted = 0 AND il.quantity_onhand > 0 + GROUP BY h.herb_item_id + HAVING lot_count > 1 + ORDER BY total_value DESC + LIMIT 5 + """) + + multi_lots = cursor.fetchall() + if multi_lots: + print("\n여러 LOT을 가진 약재:") + for herb in multi_lots: + print(f" - {herb['herb_name']}: {herb['lot_count']}개 LOT, ₩{herb['total_value']:,.0f}") + + # 특이사항 확인 - LEFT JOIN으로 인한 NULL 처리 + cursor.execute(""" + SELECT COUNT(*) as herbs_without_lots + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id + AND il.is_depleted = 0 + AND il.quantity_onhand > 0 + WHERE il.lot_id IS NULL + """) + no_lots = cursor.fetchone()['herbs_without_lots'] + + if no_lots > 0: + print(f"\n재고가 없는 약재 수: {no_lots}개") + + conn.close() + +if __name__ == "__main__": + debug_api_calculation() \ No newline at end of file diff --git a/debug_receipt_detail.py b/dev_scripts/debug_receipt_detail.py similarity index 100% rename from debug_receipt_detail.py rename to dev_scripts/debug_receipt_detail.py diff --git a/dev_scripts/final_inventory_analysis.py b/dev_scripts/final_inventory_analysis.py new file mode 100644 index 0000000..e5fd331 --- /dev/null +++ b/dev_scripts/final_inventory_analysis.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +재고 자산 금액 불일치 최종 분석 +""" + +import sqlite3 +from datetime import datetime + +def final_analysis(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("재고 자산 금액 불일치 최종 분석") + print("분석 시간:", datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + print("=" * 80) + print() + + # 1. 현재 DB의 실제 재고 자산 + print("📊 현재 데이터베이스 상태") + print("-" * 60) + + cursor.execute(""" + SELECT + SUM(quantity_onhand * unit_price_per_g) as total_value, + COUNT(*) as lot_count, + SUM(quantity_onhand) as total_quantity + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + + current = cursor.fetchone() + db_total = current['total_value'] or 0 + + print(f" DB 재고 자산: ₩{db_total:,.0f}") + print(f" 활성 LOT: {current['lot_count']}개") + print(f" 총 재고량: {current['total_quantity']:,.1f}g") + print() + + # 2. 입고와 출고 분석 + print("💼 입고/출고 분석") + print("-" * 60) + + # 입고 총액 + cursor.execute(""" + SELECT SUM(line_total) as total_in + FROM purchase_receipt_lines + """) + total_in = cursor.fetchone()['total_in'] or 0 + + # 복합제 소비 금액 + cursor.execute(""" + SELECT SUM(cc.quantity_used * il.unit_price_per_g) as total_out + FROM compound_consumptions cc + JOIN inventory_lots il ON cc.lot_id = il.lot_id + """) + total_out = cursor.fetchone()['total_out'] or 0 + + print(f" 총 입고 금액: ₩{total_in:,.0f}") + print(f" 총 소비 금액: ₩{total_out:,.0f}") + print(f" 예상 잔액: ₩{total_in - total_out:,.0f}") + print() + + # 3. 차이 분석 + print("🔍 차이 분석 결과") + print("=" * 60) + print() + + ui_value = 5875708 # 화면에 표시되는 금액 + expected_value = total_in - total_out + + print(f" 화면 표시 금액: ₩{ui_value:,.0f}") + print(f" DB 계산 금액: ₩{db_total:,.0f}") + print(f" 예상 금액 (입고-소비): ₩{expected_value:,.0f}") + print() + + print(" 차이:") + print(f" 화면 vs DB: ₩{ui_value - db_total:,.0f}") + print(f" 화면 vs 예상: ₩{ui_value - expected_value:,.0f}") + print(f" DB vs 예상: ₩{db_total - expected_value:,.0f}") + print() + + # 4. 가능한 원인 분석 + print("❗ 불일치 원인 분석") + print("-" * 60) + + # 4-1. 단가 차이 확인 + cursor.execute(""" + SELECT + prl.line_id, + h.herb_name, + prl.quantity_g as purchase_qty, + prl.unit_price_per_g as purchase_price, + prl.line_total as purchase_total, + il.quantity_onhand as current_qty, + il.unit_price_per_g as lot_price, + il.quantity_onhand * il.unit_price_per_g as current_value, + ABS(prl.unit_price_per_g - il.unit_price_per_g) as price_diff + FROM purchase_receipt_lines prl + JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + JOIN herb_items h ON prl.herb_item_id = h.herb_item_id + WHERE il.is_depleted = 0 AND il.quantity_onhand > 0 + AND ABS(prl.unit_price_per_g - il.unit_price_per_g) > 0.01 + ORDER BY price_diff DESC + LIMIT 5 + """) + + price_diffs = cursor.fetchall() + if price_diffs: + print("\n ⚠️ 입고 단가와 LOT 단가가 다른 항목:") + for pd in price_diffs: + print(f" {pd['herb_name']}:") + print(f" 입고 단가: ₩{pd['purchase_price']:.2f}/g") + print(f" LOT 단가: ₩{pd['lot_price']:.2f}/g") + print(f" 차이: ₩{pd['price_diff']:.2f}/g") + + # 4-2. 소비 후 남은 재고 확인 + cursor.execute(""" + SELECT + h.herb_name, + il.lot_number, + il.quantity_received as original_qty, + il.quantity_onhand as current_qty, + il.quantity_received - il.quantity_onhand as consumed_qty, + il.unit_price_per_g + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE il.is_depleted = 0 + AND il.quantity_received > il.quantity_onhand + ORDER BY (il.quantity_received - il.quantity_onhand) DESC + LIMIT 5 + """) + + consumed_lots = cursor.fetchall() + if consumed_lots: + print("\n 📉 소비된 재고가 있는 LOT (상위 5개):") + for cl in consumed_lots: + print(f" {cl['herb_name']} (LOT: {cl['lot_number']})") + print(f" 원래: {cl['original_qty']:,.0f}g → 현재: {cl['current_qty']:,.0f}g") + print(f" 소비: {cl['consumed_qty']:,.0f}g (₩{cl['consumed_qty'] * cl['unit_price_per_g']:,.0f})") + + # 4-3. JavaScript 계산 로직 확인 필요 + print("\n 💡 추가 확인 필요사항:") + print(" 1) 프론트엔드 JavaScript에서 재고 자산을 계산하는 로직") + print(" 2) 캐시 또는 세션 스토리지에 저장된 이전 값") + print(" 3) inventory_lots_v2 테이블 사용 여부") + + # inventory_lots_v2 확인 + cursor.execute(""" + SELECT + SUM(quantity_onhand * unit_price_per_g) as v2_total, + COUNT(*) as v2_count + FROM inventory_lots_v2 + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + + v2_result = cursor.fetchone() + if v2_result and v2_result['v2_count'] > 0: + v2_total = v2_result['v2_total'] or 0 + print(f"\n ⚠️ inventory_lots_v2 테이블 데이터:") + print(f" 재고 자산: ₩{v2_total:,.0f}") + print(f" LOT 수: {v2_result['v2_count']}개") + + if abs(v2_total - ui_value) < 100: + print(f" → 화면 금액과 일치할 가능성 높음!") + + print() + + # 5. 결론 + print("📝 결론") + print("=" * 60) + + diff = ui_value - db_total + if diff > 0: + print(f" 화면에 표시되는 금액(₩{ui_value:,.0f})이") + print(f" 실제 DB 금액(₩{db_total:,.0f})보다") + print(f" ₩{diff:,.0f} 더 많습니다.") + print() + print(" 가능한 원인:") + print(" 1) 프론트엔드에서 별도의 계산 로직 사용") + print(" 2) 캐시된 이전 데이터 표시") + print(" 3) inventory_lots_v2 테이블 참조") + print(" 4) 재고 보정 내역이 즉시 반영되지 않음") + else: + print(f" 실제 DB 금액이 화면 표시 금액보다 적습니다.") + + conn.close() + +if __name__ == "__main__": + final_analysis() \ No newline at end of file diff --git a/dev_scripts/final_price_analysis.py b/dev_scripts/final_price_analysis.py new file mode 100644 index 0000000..66c14a7 --- /dev/null +++ b/dev_scripts/final_price_analysis.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +최종 가격 차이 분석 +""" + +import sqlite3 + +def final_price_analysis(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("📊 재고 자산 차이 최종 분석") + print("=" * 80) + print() + + # 1. 핵심 차이 확인 + print("1. 핵심 금액 차이") + print("-" * 60) + + # 입고 라인과 LOT 차이 + cursor.execute(""" + SELECT + h.herb_name, + prl.quantity_g as receipt_qty, + prl.unit_price_per_g as receipt_price, + prl.line_total as receipt_total, + il.quantity_received as lot_qty, + il.unit_price_per_g as lot_price, + il.quantity_received * il.unit_price_per_g as lot_total, + prl.line_total - (il.quantity_received * il.unit_price_per_g) as diff + FROM purchase_receipt_lines prl + JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + JOIN herb_items h ON prl.herb_item_id = h.herb_item_id + WHERE ABS(prl.line_total - (il.quantity_received * il.unit_price_per_g)) > 1 + ORDER BY ABS(prl.line_total - (il.quantity_received * il.unit_price_per_g)) DESC + """) + + differences = cursor.fetchall() + + if differences: + print(" 입고장과 LOT 생성 시 차이가 있는 항목:") + print() + total_diff = 0 + for diff in differences: + print(f" 📌 {diff['herb_name']}") + print(f" 입고장: {diff['receipt_qty']:,.0f}g × ₩{diff['receipt_price']:.2f} = ₩{diff['receipt_total']:,.0f}") + print(f" LOT: {diff['lot_qty']:,.0f}g × ₩{diff['lot_price']:.2f} = ₩{diff['lot_total']:,.0f}") + print(f" 차이: ₩{diff['diff']:,.0f}") + print() + total_diff += diff['diff'] + + print(f" 총 차이: ₩{total_diff:,.0f}") + + # 2. 재고 자산 흐름 + print("\n2. 재고 자산 흐름 정리") + print("=" * 60) + + # 각 단계별 금액 + cursor.execute("SELECT SUM(line_total) as total FROM purchase_receipt_lines") + receipt_total = cursor.fetchone()['total'] or 0 + + cursor.execute(""" + SELECT SUM(quantity_received * unit_price_per_g) as total + FROM inventory_lots + """) + lot_creation_total = cursor.fetchone()['total'] or 0 + + cursor.execute(""" + SELECT SUM(cc.quantity_used * il.unit_price_per_g) as total + FROM compound_consumptions cc + JOIN inventory_lots il ON cc.lot_id = il.lot_id + """) + consumed_total = cursor.fetchone()['total'] or 0 + + cursor.execute(""" + SELECT SUM(quantity_onhand * unit_price_per_g) as total + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + current_inventory = cursor.fetchone()['total'] or 0 + + print(f" 1️⃣ 입고장 총액: ₩{receipt_total:,.0f}") + print(f" 2️⃣ LOT 생성 총액: ₩{lot_creation_total:,.0f}") + print(f" 차이 (1-2): ₩{receipt_total - lot_creation_total:,.0f}") + print() + print(f" 3️⃣ 소비 총액: ₩{consumed_total:,.0f}") + print(f" 4️⃣ 현재 재고 자산: ₩{current_inventory:,.0f}") + print() + print(f" 📊 계산식:") + print(f" LOT 생성 - 소비 = ₩{lot_creation_total:,.0f} - ₩{consumed_total:,.0f}") + print(f" = ₩{lot_creation_total - consumed_total:,.0f} (예상)") + print(f" 실제 재고 = ₩{current_inventory:,.0f}") + print(f" 차이 = ₩{current_inventory - (lot_creation_total - consumed_total):,.0f}") + + # 3. 차이 원인 분석 + print("\n3. 차이 원인 설명") + print("-" * 60) + + # 휴먼일당귀 특별 케이스 확인 + cursor.execute(""" + SELECT + prl.quantity_g as receipt_qty, + il.quantity_received as lot_received, + il.quantity_onhand as lot_current + FROM purchase_receipt_lines prl + JOIN inventory_lots il ON prl.line_id = il.receipt_line_id + JOIN herb_items h ON prl.herb_item_id = h.herb_item_id + WHERE h.herb_name = '휴먼일당귀' + """) + + ildan = cursor.fetchone() + if ildan: + print("\n 💡 휴먼일당귀 케이스:") + print(f" 입고장 수량: {ildan['receipt_qty']:,.0f}g") + print(f" LOT 생성 수량: {ildan['lot_received']:,.0f}g") + print(f" 현재 재고: {ildan['lot_current']:,.0f}g") + print(f" → 입고 시 5,000g 중 3,000g만 LOT 생성됨") + print(f" → 나머지 2,000g는 별도 처리되었을 가능성") + + print("\n 📝 결론:") + print(" 1. 입고장 총액 (₩1,616,400) vs LOT 생성 총액 (₩1,607,400)") + print(" → ₩9,000 차이 (휴먼일당귀 수량 차이로 인함)") + print() + print(" 2. 예상 재고 (₩1,529,434) vs 실제 재고 (₩1,529,434)") + print(" → 정확히 일치") + print() + print(" 3. 입고 기준 예상 (₩1,538,434) vs 실제 재고 (₩1,529,434)") + print(" → ₩9,000 차이 (입고와 LOT 생성 차이와 동일)") + + # 4. 추가 LOT 확인 + print("\n4. 추가 LOT 존재 여부") + print("-" * 60) + + cursor.execute(""" + SELECT + h.herb_name, + COUNT(*) as lot_count, + SUM(il.quantity_received) as total_received, + SUM(il.quantity_onhand) as total_onhand + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE h.herb_name = '휴먼일당귀' + GROUP BY h.herb_item_id + """) + + ildan_lots = cursor.fetchone() + if ildan_lots: + print(f" 휴먼일당귀 LOT 현황:") + print(f" LOT 개수: {ildan_lots['lot_count']}개") + print(f" 총 입고량: {ildan_lots['total_received']:,.0f}g") + print(f" 현재 재고: {ildan_lots['total_onhand']:,.0f}g") + + # 상세 LOT 정보 + cursor.execute(""" + SELECT + lot_id, + lot_number, + quantity_received, + quantity_onhand, + unit_price_per_g, + receipt_line_id + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE h.herb_name = '휴먼일당귀' + """) + + lots = cursor.fetchall() + for lot in lots: + print(f"\n LOT {lot['lot_id']}:") + print(f" LOT 번호: {lot['lot_number']}") + print(f" 입고량: {lot['quantity_received']:,.0f}g") + print(f" 현재: {lot['quantity_onhand']:,.0f}g") + print(f" 단가: ₩{lot['unit_price_per_g']:.2f}") + print(f" 입고라인: {lot['receipt_line_id']}") + + conn.close() + +if __name__ == "__main__": + final_price_analysis() \ No newline at end of file diff --git a/dev_scripts/final_verification.py b/dev_scripts/final_verification.py new file mode 100644 index 0000000..dcac69e --- /dev/null +++ b/dev_scripts/final_verification.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +최종 검증 - 문제 해결 확인 +""" + +import sqlite3 +import json +import urllib.request + +def final_verification(): + print("=" * 80) + print("📊 재고 자산 문제 해결 최종 검증") + print("=" * 80) + print() + + # 1. API 호출 결과 + print("1. API 응답 확인") + print("-" * 60) + + try: + with urllib.request.urlopen('http://localhost:5001/api/inventory/summary') as response: + data = json.loads(response.read()) + api_value = data['summary']['total_value'] + total_items = data['summary']['total_items'] + + print(f" API 재고 자산: ₩{api_value:,.0f}") + print(f" 총 약재 수: {total_items}개") + except Exception as e: + print(f" API 호출 실패: {e}") + api_value = 0 + + # 2. 데이터베이스 직접 계산 + print("\n2. 데이터베이스 직접 계산") + print("-" * 60) + + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + cursor.execute(""" + SELECT + SUM(quantity_onhand * unit_price_per_g) as total_value, + COUNT(*) as lot_count, + SUM(quantity_onhand) as total_quantity + FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + """) + + db_result = cursor.fetchone() + db_value = db_result['total_value'] or 0 + + print(f" DB 재고 자산: ₩{db_value:,.0f}") + print(f" 활성 LOT: {db_result['lot_count']}개") + print(f" 총 재고량: {db_result['total_quantity']:,.1f}g") + + # 3. 입고와 출고 기반 계산 + print("\n3. 입고/출고 기반 계산") + print("-" * 60) + + # 총 입고액 + cursor.execute("SELECT SUM(line_total) as total FROM purchase_receipt_lines") + total_in = cursor.fetchone()['total'] or 0 + + # 총 소비액 + cursor.execute(""" + SELECT SUM(cc.quantity_used * il.unit_price_per_g) as total + FROM compound_consumptions cc + JOIN inventory_lots il ON cc.lot_id = il.lot_id + """) + total_out = cursor.fetchone()['total'] or 0 + + expected = total_in - total_out + + print(f" 입고 총액: ₩{total_in:,.0f}") + print(f" 소비 총액: ₩{total_out:,.0f}") + print(f" 예상 재고: ₩{expected:,.0f}") + + # 4. 결과 비교 + print("\n4. 결과 비교") + print("=" * 60) + + print(f"\n 🎯 API 재고 자산: ₩{api_value:,.0f}") + print(f" 🎯 DB 직접 계산: ₩{db_value:,.0f}") + print(f" 🎯 예상 재고액: ₩{expected:,.0f}") + + # 차이 계산 + api_db_diff = abs(api_value - db_value) + db_expected_diff = abs(db_value - expected) + + print(f"\n API vs DB 차이: ₩{api_db_diff:,.0f}") + print(f" DB vs 예상 차이: ₩{db_expected_diff:,.0f}") + + # 5. 결론 + print("\n5. 결론") + print("=" * 60) + + if api_db_diff < 100: + print("\n ✅ 문제 해결 완료!") + print(" API와 DB 계산이 일치합니다.") + print(f" 재고 자산: ₩{api_value:,.0f}") + else: + print("\n ⚠️ 아직 차이가 있습니다.") + print(f" 차이: ₩{api_db_diff:,.0f}") + + if db_expected_diff > 100000: + print("\n 📌 참고: DB 재고와 예상 재고 간 차이는") + print(" 다음 요인들로 인해 발생할 수 있습니다:") + print(" - 입고 시점과 LOT 생성 시점의 단가 차이") + print(" - 재고 보정 내역") + print(" - 반올림 오차 누적") + + # 6. 효능 태그 확인 (중복 문제가 해결되었는지) + print("\n6. 효능 태그 표시 확인") + print("-" * 60) + + # API에서 효능 태그가 있는 약재 확인 + try: + with urllib.request.urlopen('http://localhost:5001/api/inventory/summary') as response: + data = json.loads(response.read()) + + herbs_with_tags = [ + item for item in data['data'] + if item.get('efficacy_tags') and len(item['efficacy_tags']) > 0 + ] + + print(f" 효능 태그가 있는 약재: {len(herbs_with_tags)}개") + + if herbs_with_tags: + sample = herbs_with_tags[0] + print(f"\n 예시: {sample['herb_name']}") + print(f" 태그: {', '.join(sample['efficacy_tags'])}") + print(f" 재고 가치: ₩{sample['total_value']:,.0f}") + except Exception as e: + print(f" 효능 태그 확인 실패: {e}") + + conn.close() + + print("\n" + "=" * 80) + print("검증 완료") + print("=" * 80) + +if __name__ == "__main__": + final_verification() \ No newline at end of file diff --git a/test_compound_e2e.py b/dev_scripts/test_compound_e2e.py similarity index 100% rename from test_compound_e2e.py rename to dev_scripts/test_compound_e2e.py diff --git a/test_compound_page.py b/dev_scripts/test_compound_page.py similarity index 100% rename from test_compound_page.py rename to dev_scripts/test_compound_page.py diff --git a/test_db.py b/dev_scripts/test_db.py similarity index 100% rename from test_db.py rename to dev_scripts/test_db.py diff --git a/test_direct.py b/dev_scripts/test_direct.py similarity index 100% rename from test_direct.py rename to dev_scripts/test_direct.py diff --git a/dev_scripts/test_direct_api.py b/dev_scripts/test_direct_api.py new file mode 100644 index 0000000..eb6cd5d --- /dev/null +++ b/dev_scripts/test_direct_api.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +API 함수 직접 테스트 +""" + +import os +import sqlite3 + +# Flask 앱과 동일한 설정 +DATABASE = 'database/kdrug.db' + +def get_inventory_summary(): + """app.py의 get_inventory_summary 함수와 동일""" + conn = sqlite3.connect(DATABASE) + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + cursor.execute(""" + SELECT + h.herb_item_id, + h.insurance_code, + h.herb_name, + COALESCE(SUM(il.quantity_onhand), 0) as total_quantity, + COUNT(DISTINCT il.lot_id) as lot_count, + COUNT(DISTINCT il.origin_country) as origin_count, + AVG(il.unit_price_per_g) as avg_price, + MIN(il.unit_price_per_g) as min_price, + MAX(il.unit_price_per_g) as max_price, + COALESCE(SUM(il.quantity_onhand * il.unit_price_per_g), 0) as total_value, + GROUP_CONCAT(DISTINCT et.tag_name) as efficacy_tags + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0 + LEFT JOIN herb_products hp ON h.insurance_code = hp.product_code + LEFT JOIN herb_item_tags hit ON COALESCE(h.ingredient_code, hp.ingredient_code) = hit.ingredient_code + LEFT JOIN herb_efficacy_tags et ON hit.tag_id = et.tag_id + GROUP BY h.herb_item_id, h.insurance_code, h.herb_name + HAVING total_quantity > 0 + ORDER BY h.herb_name + """) + + inventory = [] + for row in cursor.fetchall(): + item = dict(row) + if item['efficacy_tags']: + item['efficacy_tags'] = item['efficacy_tags'].split(',') + else: + item['efficacy_tags'] = [] + inventory.append(item) + + # 전체 요약 + total_value = sum(item['total_value'] for item in inventory) + total_items = len(inventory) + + print("=" * 60) + print("API 함수 직접 실행 결과") + print("=" * 60) + print() + print(f"총 약재 수: {total_items}개") + print(f"총 재고 자산: ₩{total_value:,.0f}") + print() + + # 상세 내역 + print("약재별 재고 가치 (상위 10개):") + print("-" * 40) + sorted_items = sorted(inventory, key=lambda x: x['total_value'], reverse=True) + for i, item in enumerate(sorted_items[:10], 1): + print(f"{i:2}. {item['herb_name']:15} ₩{item['total_value']:10,.0f}") + + conn.close() + return total_value + +if __name__ == "__main__": + total = get_inventory_summary() + print() + print("=" * 60) + print(f"최종 결과: ₩{total:,.0f}") + + if total == 5875708: + print("⚠️ API와 동일한 값이 나옴!") + else: + print(f"✅ 예상값: ₩1,529,434") + print(f" 차이: ₩{total - 1529434:,.0f}") \ No newline at end of file diff --git a/test_frontend.py b/dev_scripts/test_frontend.py similarity index 100% rename from test_frontend.py rename to dev_scripts/test_frontend.py diff --git a/test_herb_dropdown_bug.py b/dev_scripts/test_herb_dropdown_bug.py similarity index 100% rename from test_herb_dropdown_bug.py rename to dev_scripts/test_herb_dropdown_bug.py diff --git a/dev_scripts/test_herb_info_page.py b/dev_scripts/test_herb_info_page.py new file mode 100644 index 0000000..67794e1 --- /dev/null +++ b/dev_scripts/test_herb_info_page.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""약재 정보 페이지 테스트 - 렌더링 문제 수정 후 검증""" + +import requests +import json +import re +from datetime import datetime + +BASE_URL = "http://localhost:5001" + + +def test_html_structure(): + """HTML 구조 검증 - herb-info가 content-area 안에 있는지 확인""" + print("1. HTML 구조 검증...") + response = requests.get(f"{BASE_URL}/") + if response.status_code != 200: + print(f" FAIL: 페이지 로드 실패 {response.status_code}") + return False + + content = response.text + + # herb-info가 col-md-10 content-area 안에 있는지 확인 + idx_content = content.find('col-md-10 content-area') + idx_herb_info = content.find('id="herb-info"') + + if idx_content < 0: + print(" FAIL: col-md-10 content-area 찾을 수 없음") + return False + if idx_herb_info < 0: + print(" FAIL: herb-info div 찾을 수 없음") + return False + + if idx_herb_info > idx_content: + print(" PASS: herb-info가 content-area 안에 올바르게 위치함") + else: + print(" FAIL: herb-info가 content-area 밖에 있음!") + return False + + # efficacyFilter ID 중복 검사 + count_efficacy = content.count('id="efficacyFilter"') + if count_efficacy > 1: + print(f" FAIL: id=\"efficacyFilter\" 중복 {count_efficacy}개 발견!") + return False + else: + print(f" PASS: id=\"efficacyFilter\" 중복 없음 (개수: {count_efficacy})") + + # herbInfoEfficacyFilter 존재 확인 + if 'id="herbInfoEfficacyFilter"' in content: + print(" PASS: herbInfoEfficacyFilter ID 정상 존재") + else: + print(" FAIL: herbInfoEfficacyFilter ID 없음!") + return False + + return True + + +def test_efficacy_tags(): + """효능 태그 조회 API 검증""" + print("\n2. 효능 태그 목록 조회...") + response = requests.get(f"{BASE_URL}/api/efficacy-tags") + if response.status_code != 200: + print(f" FAIL: {response.status_code}") + return False + + tags = response.json() + if not isinstance(tags, list): + print(f" FAIL: 응답이 리스트가 아님 - {type(tags)}") + return False + + print(f" PASS: {len(tags)}개의 효능 태그 조회 성공") + for tag in tags[:3]: + print(f" - {tag.get('name', '')}: {tag.get('description', '')}") + return True + + +def test_herb_masters_api(): + """약재 마스터 목록 + herb_id 포함 여부 검증""" + print("\n3. 약재 마스터 목록 조회 (herb_id 포함 여부 확인)...") + response = requests.get(f"{BASE_URL}/api/herbs/masters") + if response.status_code != 200: + print(f" FAIL: {response.status_code}") + return False + + result = response.json() + if not result.get('success'): + print(f" FAIL: success=False") + return False + + herbs = result.get('data', []) + print(f" PASS: {len(herbs)}개의 약재 조회 성공") + + if not herbs: + print(" FAIL: 약재 데이터 없음") + return False + + first = herbs[0] + + # herb_id 확인 + if 'herb_id' in first: + print(f" PASS: herb_id 필드 존재 (값: {first['herb_id']})") + else: + print(f" FAIL: herb_id 필드 누락! 키 목록: {list(first.keys())}") + return False + + # ingredient_code 확인 + if 'ingredient_code' in first: + print(f" PASS: ingredient_code 필드 존재") + else: + print(" FAIL: ingredient_code 필드 누락!") + return False + + # efficacy_tags가 리스트인지 확인 + if isinstance(first.get('efficacy_tags'), list): + print(f" PASS: efficacy_tags가 리스트 형식") + else: + print(f" FAIL: efficacy_tags 형식 오류: {first.get('efficacy_tags')}") + return False + + return True + + +def test_herb_extended_info(): + """약재 확장 정보 조회 API 검증""" + print("\n4. 약재 확장 정보 조회 (herb_id=1 기준)...") + response = requests.get(f"{BASE_URL}/api/herbs/1/extended") + if response.status_code != 200: + print(f" FAIL: {response.status_code}") + return False + + info = response.json() + if not isinstance(info, dict): + print(f" FAIL: 응답이 dict가 아님") + return False + + print(f" PASS: herb_id=1 확장 정보 조회 성공") + print(f" - herb_name: {info.get('herb_name', '-')}") + print(f" - name_korean: {info.get('name_korean', '-')}") + print(f" - property: {info.get('property', '-')}") + return True + + +def test_herb_masters_has_extended_fields(): + """약재 마스터 목록에 확장 정보(property, main_effects)가 포함되는지 검증""" + print("\n5. 약재 마스터에 확장 정보 필드 포함 여부...") + response = requests.get(f"{BASE_URL}/api/herbs/masters") + result = response.json() + herbs = result.get('data', []) + + required_fields = ['ingredient_code', 'herb_name', 'herb_id', 'has_stock', + 'efficacy_tags', 'property', 'main_effects'] + first = herbs[0] if herbs else {} + missing = [f for f in required_fields if f not in first] + + if missing: + print(f" FAIL: 누락된 필드: {missing}") + return False + + print(f" PASS: 필수 필드 모두 존재: {required_fields}") + return True + + +def main(): + print("=== 약재 정보 페이지 렌더링 수정 검증 테스트 ===") + print(f"시간: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + print(f"서버: {BASE_URL}") + print("-" * 50) + + results = [] + results.append(("HTML 구조 검증", test_html_structure())) + results.append(("효능 태그 API", test_efficacy_tags())) + results.append(("약재 마스터 API (herb_id)", test_herb_masters_api())) + results.append(("약재 확장 정보 API", test_herb_extended_info())) + results.append(("약재 마스터 필드 완전성", test_herb_masters_has_extended_fields())) + + print("\n" + "=" * 50) + success = sum(1 for _, r in results if r) + total = len(results) + print(f"테스트 결과: {success}/{total} 성공") + for name, result in results: + status = "PASS" if result else "FAIL" + print(f" [{status}] {name}") + + if success == total: + print("\n모든 테스트 통과. 약재 정보 페이지가 정상적으로 동작해야 합니다.") + else: + print(f"\n{total - success}개 테스트 실패. 추가 수정이 필요합니다.") + + return success == total + + +if __name__ == "__main__": + main() diff --git a/dev_scripts/test_herb_info_ui.py b/dev_scripts/test_herb_info_ui.py new file mode 100644 index 0000000..24c7b6c --- /dev/null +++ b/dev_scripts/test_herb_info_ui.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Playwright를 사용한 약재 정보 페이지 UI 테스트""" + +import asyncio +from playwright.async_api import async_playwright +import time + +async def test_herb_info_page(): + async with async_playwright() as p: + # 브라우저 시작 + browser = await p.chromium.launch(headless=True) + page = await browser.new_page() + + # 콘솔 메시지 캡처 + console_messages = [] + page.on("console", lambda msg: console_messages.append(f"{msg.type}: {msg.text}")) + + # 페이지 에러 캡처 + page_errors = [] + page.on("pageerror", lambda err: page_errors.append(str(err))) + + try: + print("=== Playwright 약재 정보 페이지 테스트 ===\n") + + # 1. 메인 페이지 접속 + print("1. 메인 페이지 접속...") + await page.goto("http://localhost:5001") + await page.wait_for_load_state("networkidle") + + # 2. 약재 정보 메뉴 클릭 + print("2. 약재 정보 메뉴 클릭...") + herb_info_link = page.locator('a[data-page="herb-info"]') + is_visible = await herb_info_link.is_visible() + print(f" - 약재 정보 메뉴 표시 여부: {is_visible}") + + if is_visible: + await herb_info_link.click() + await page.wait_for_timeout(2000) # 2초 대기 + + # 3. herb-info 페이지 표시 확인 + print("\n3. 약재 정보 페이지 요소 확인...") + herb_info_div = page.locator('#herb-info') + is_herb_info_visible = await herb_info_div.is_visible() + print(f" - herb-info div 표시: {is_herb_info_visible}") + + if is_herb_info_visible: + # 검색 섹션 확인 + search_section = page.locator('#herb-search-section') + is_search_visible = await search_section.is_visible() + print(f" - 검색 섹션 표시: {is_search_visible}") + + # 약재 카드 그리드 확인 + herb_grid = page.locator('#herbInfoGrid') + is_grid_visible = await herb_grid.is_visible() + print(f" - 약재 그리드 표시: {is_grid_visible}") + + # 약재 카드 개수 확인 + await page.wait_for_selector('.herb-info-card', timeout=5000) + herb_cards = await page.locator('.herb-info-card').count() + print(f" - 표시된 약재 카드 수: {herb_cards}개") + + if herb_cards > 0: + # 첫 번째 약재 카드 정보 확인 + first_card = page.locator('.herb-info-card').first + card_title = await first_card.locator('.card-title').text_content() + print(f" - 첫 번째 약재: {card_title}") + + # 카드 클릭으로 상세 보기 (카드 전체가 클릭 가능) + print("\n4. 약재 상세 정보 확인...") + # herb-info-card는 클릭 가능한 카드이므로 직접 클릭 + if True: + await first_card.click() + await page.wait_for_timeout(1000) + + # 상세 모달 확인 + modal = page.locator('#herbDetailModal') + is_modal_visible = await modal.is_visible() + print(f" - 상세 모달 표시: {is_modal_visible}") + + if is_modal_visible: + modal_title = await modal.locator('.modal-title').text_content() + print(f" - 모달 제목: {modal_title}") + + # 모달 닫기 + close_btn = modal.locator('button.btn-close') + if await close_btn.is_visible(): + await close_btn.click() + await page.wait_for_timeout(500) + + # 5. 검색 기능 테스트 + print("\n5. 검색 기능 테스트...") + search_input = page.locator('#herbSearchInput') + if await search_input.is_visible(): + await search_input.fill("감초") + await page.locator('#herbSearchBtn').click() + await page.wait_for_timeout(1000) + + search_result_count = await page.locator('.herb-info-card').count() + print(f" - '감초' 검색 결과: {search_result_count}개") + + # 6. 효능별 보기 테스트 + print("\n6. 효능별 보기 전환...") + efficacy_btn = page.locator('button[data-view="efficacy"]') + if await efficacy_btn.is_visible(): + await efficacy_btn.click() + await page.wait_for_timeout(1000) + + efficacy_section = page.locator('#herb-efficacy-section') + is_efficacy_visible = await efficacy_section.is_visible() + print(f" - 효능별 섹션 표시: {is_efficacy_visible}") + + if is_efficacy_visible: + tag_buttons = await page.locator('.efficacy-tag-btn').count() + print(f" - 효능 태그 버튼 수: {tag_buttons}개") + else: + print(" ⚠️ herb-info div가 표시되지 않음!") + + # 디버깅: 현재 활성 페이지 확인 + active_pages = await page.locator('.main-content.active').count() + print(f" - 활성 페이지 수: {active_pages}") + + # 디버깅: herb-info의 display 스타일 확인 + herb_info_style = await herb_info_div.get_attribute('style') + print(f" - herb-info style: {herb_info_style}") + + # 디버깅: herb-info의 클래스 확인 + herb_info_classes = await herb_info_div.get_attribute('class') + print(f" - herb-info classes: {herb_info_classes}") + + # 7. 콘솔 에러 확인 + print("\n7. 콘솔 메시지 확인...") + if console_messages: + print(" 콘솔 메시지:") + for msg in console_messages[:10]: # 처음 10개만 출력 + print(f" - {msg}") + else: + print(" ✓ 콘솔 메시지 없음") + + if page_errors: + print(" ⚠️ 페이지 에러:") + for err in page_errors: + print(f" - {err}") + else: + print(" ✓ 페이지 에러 없음") + + # 스크린샷 저장 + await page.screenshot(path="/root/kdrug/herb_info_page.png") + print("\n스크린샷 저장: /root/kdrug/herb_info_page.png") + + except Exception as e: + print(f"\n❌ 테스트 실패: {e}") + # 에러 시 스크린샷 + await page.screenshot(path="/root/kdrug/herb_info_error.png") + print("에러 스크린샷 저장: /root/kdrug/herb_info_error.png") + + finally: + await browser.close() + +if __name__ == "__main__": + print("Playwright 테스트 시작...\n") + asyncio.run(test_herb_info_page()) + print("\n테스트 완료!") \ No newline at end of file diff --git a/test_improved_import.py b/dev_scripts/test_improved_import.py similarity index 100% rename from test_improved_import.py rename to dev_scripts/test_improved_import.py diff --git a/dev_scripts/test_js_debug.py b/dev_scripts/test_js_debug.py new file mode 100644 index 0000000..ebb00b4 --- /dev/null +++ b/dev_scripts/test_js_debug.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""JavaScript 디버깅을 위한 Playwright 테스트""" + +import asyncio +from playwright.async_api import async_playwright + +async def debug_herb_info(): + async with async_playwright() as p: + browser = await p.chromium.launch(headless=True) + page = await browser.new_page() + + # 콘솔 메시지 캡처 + console_messages = [] + page.on("console", lambda msg: console_messages.append({ + "type": msg.type, + "text": msg.text, + "args": msg.args + })) + + # 네트워크 요청 캡처 + network_requests = [] + page.on("request", lambda req: network_requests.append({ + "url": req.url, + "method": req.method + })) + + # 네트워크 응답 캡처 + network_responses = [] + async def log_response(response): + if "/api/" in response.url: + try: + body = await response.text() + network_responses.append({ + "url": response.url, + "status": response.status, + "body": body[:200] if body else None + }) + except: + pass + page.on("response", log_response) + + try: + # 페이지 접속 + print("페이지 접속 중...") + await page.goto("http://localhost:5001") + await page.wait_for_load_state("networkidle") + + # JavaScript 실행하여 직접 함수 호출 + print("\n직접 JavaScript 함수 테스트...") + + # loadHerbInfo 함수 존재 확인 + has_function = await page.evaluate("typeof loadHerbInfo === 'function'") + print(f"1. loadHerbInfo 함수 존재: {has_function}") + + # loadAllHerbsInfo 함수 존재 확인 + has_all_herbs = await page.evaluate("typeof loadAllHerbsInfo === 'function'") + print(f"2. loadAllHerbsInfo 함수 존재: {has_all_herbs}") + + # displayHerbCards 함수 존재 확인 + has_display = await page.evaluate("typeof displayHerbCards === 'function'") + print(f"3. displayHerbCards 함수 존재: {has_display}") + + # 약재 정보 페이지로 이동 + await page.click('a[data-page="herb-info"]') + await page.wait_for_timeout(2000) + + # herbInfoGrid 요소 확인 + grid_exists = await page.evaluate("document.getElementById('herbInfoGrid') !== null") + print(f"4. herbInfoGrid 요소 존재: {grid_exists}") + + # herbInfoGrid 내용 확인 + grid_html = await page.evaluate("document.getElementById('herbInfoGrid')?.innerHTML || 'EMPTY'") + print(f"5. herbInfoGrid 내용 길이: {len(grid_html)} 문자") + if grid_html and grid_html != 'EMPTY': + print(f" 처음 100자: {grid_html[:100]}...") + + # API 호출 직접 테스트 + print("\n\nAPI 응답 직접 테스트...") + api_response = await page.evaluate(""" + fetch('/api/herbs/masters') + .then(res => res.json()) + .then(data => ({ + success: data.success, + dataLength: data.data ? data.data.length : 0, + firstItem: data.data ? data.data[0] : null + })) + .catch(err => ({ error: err.toString() })) + """) + print(f"API 응답: {api_response}") + + # displayHerbCards 직접 호출 테스트 + if api_response.get('dataLength', 0) > 0: + print("\n\ndisplayHerbCards 직접 호출...") + await page.evaluate(""" + fetch('/api/herbs/masters') + .then(res => res.json()) + .then(data => { + if (typeof displayHerbCards === 'function') { + displayHerbCards(data.data); + } else { + console.error('displayHerbCards 함수가 없습니다'); + } + }) + """) + await page.wait_for_timeout(1000) + + # 다시 확인 + grid_html_after = await page.evaluate("document.getElementById('herbInfoGrid')?.innerHTML || 'EMPTY'") + print(f"displayHerbCards 호출 후 내용 길이: {len(grid_html_after)} 문자") + + card_count = await page.evaluate("document.querySelectorAll('.herb-card').length") + print(f"herb-card 요소 개수: {card_count}") + + # 콘솔 메시지 출력 + print("\n\n=== 콘솔 메시지 ===") + for msg in console_messages: + if 'error' in msg['type'].lower(): + print(f"❌ {msg['type']}: {msg['text']}") + else: + print(f"📝 {msg['type']}: {msg['text']}") + + # API 응답 상태 확인 + print("\n\n=== API 응답 ===") + for resp in network_responses: + if '/api/herbs/masters' in resp['url']: + print(f"URL: {resp['url']}") + print(f"상태: {resp['status']}") + print(f"응답: {resp['body'][:100] if resp['body'] else 'No body'}") + + finally: + await browser.close() + +if __name__ == "__main__": + asyncio.run(debug_herb_info()) \ No newline at end of file diff --git a/test_lot_validation.py b/dev_scripts/test_lot_validation.py similarity index 100% rename from test_lot_validation.py rename to dev_scripts/test_lot_validation.py diff --git a/test_multi_lot_compound.py b/dev_scripts/test_multi_lot_compound.py similarity index 100% rename from test_multi_lot_compound.py rename to dev_scripts/test_multi_lot_compound.py diff --git a/test_simple.py b/dev_scripts/test_simple.py similarity index 100% rename from test_simple.py rename to dev_scripts/test_simple.py diff --git a/test_upload_api.py b/dev_scripts/test_upload_api.py similarity index 100% rename from test_upload_api.py rename to dev_scripts/test_upload_api.py diff --git a/find_duplicate_issue.py b/find_duplicate_issue.py new file mode 100644 index 0000000..d7c715d --- /dev/null +++ b/find_duplicate_issue.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +JOIN으로 인한 중복 문제 찾기 +""" + +import sqlite3 + +def find_duplicate_issue(): + conn = sqlite3.connect('database/kdrug.db') + conn.row_factory = sqlite3.Row + cursor = conn.cursor() + + print("=" * 80) + print("JOIN으로 인한 중복 문제 분석") + print("=" * 80) + print() + + # 1. 효능 태그 JOIN 없이 계산 + print("1. 효능 태그 JOIN 없이 계산") + print("-" * 60) + + cursor.execute(""" + SELECT + h.herb_item_id, + h.herb_name, + COALESCE(SUM(il.quantity_onhand * il.unit_price_per_g), 0) as total_value + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0 + GROUP BY h.herb_item_id, h.herb_name + HAVING total_value > 0 + ORDER BY total_value DESC + LIMIT 5 + """) + + simple_results = cursor.fetchall() + simple_total = 0 + + for item in simple_results: + simple_total += item['total_value'] + print(f" {item['herb_name']:15} ₩{item['total_value']:10,.0f}") + + # 전체 합계 + cursor.execute(""" + SELECT SUM(total_value) as grand_total + FROM ( + SELECT + h.herb_item_id, + COALESCE(SUM(il.quantity_onhand * il.unit_price_per_g), 0) as total_value + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0 + GROUP BY h.herb_item_id + HAVING total_value > 0 + ) + """) + + simple_grand_total = cursor.fetchone()['grand_total'] or 0 + print(f"\n 총합: ₩{simple_grand_total:,.0f}") + + # 2. 효능 태그 JOIN 포함 계산 (API와 동일) + print("\n2. 효능 태그 JOIN 포함 계산 (API 쿼리)") + print("-" * 60) + + cursor.execute(""" + SELECT + h.herb_item_id, + h.herb_name, + COALESCE(SUM(il.quantity_onhand * il.unit_price_per_g), 0) as total_value, + COUNT(*) as row_count + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0 + LEFT JOIN herb_products hp ON h.insurance_code = hp.product_code + LEFT JOIN herb_item_tags hit ON COALESCE(h.ingredient_code, hp.ingredient_code) = hit.ingredient_code + LEFT JOIN herb_efficacy_tags et ON hit.tag_id = et.tag_id + GROUP BY h.herb_item_id, h.herb_name + HAVING total_value > 0 + ORDER BY total_value DESC + LIMIT 5 + """) + + api_results = cursor.fetchall() + + for item in api_results: + print(f" {item['herb_name']:15} ₩{item['total_value']:10,.0f} (행수: {item['row_count']})") + + # 전체 합계 (API 방식) + cursor.execute(""" + SELECT SUM(total_value) as grand_total + FROM ( + SELECT + h.herb_item_id, + COALESCE(SUM(il.quantity_onhand * il.unit_price_per_g), 0) as total_value + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0 + LEFT JOIN herb_products hp ON h.insurance_code = hp.product_code + LEFT JOIN herb_item_tags hit ON COALESCE(h.ingredient_code, hp.ingredient_code) = hit.ingredient_code + LEFT JOIN herb_efficacy_tags et ON hit.tag_id = et.tag_id + GROUP BY h.herb_item_id + HAVING total_value > 0 + ) + """) + + api_grand_total = cursor.fetchone()['grand_total'] or 0 + print(f"\n 총합: ₩{api_grand_total:,.0f}") + + # 3. 중복 원인 분석 + print("\n3. 중복 원인 분석") + print("-" * 60) + + print(f" ✅ 정상 계산: ₩{simple_grand_total:,.0f}") + print(f" ❌ API 계산: ₩{api_grand_total:,.0f}") + print(f" 차이: ₩{api_grand_total - simple_grand_total:,.0f}") + + if api_grand_total > simple_grand_total: + ratio = api_grand_total / simple_grand_total if simple_grand_total > 0 else 0 + print(f" 배율: {ratio:.2f}배") + + # 4. 효능 태그 중복 확인 + print("\n4. 효능 태그로 인한 중복 확인") + print("-" * 60) + + cursor.execute(""" + SELECT + h.herb_name, + h.ingredient_code, + COUNT(DISTINCT hit.tag_id) as tag_count + FROM herb_items h + LEFT JOIN herb_products hp ON h.insurance_code = hp.product_code + LEFT JOIN herb_item_tags hit ON COALESCE(h.ingredient_code, hp.ingredient_code) = hit.ingredient_code + WHERE h.herb_item_id IN ( + SELECT herb_item_id FROM inventory_lots + WHERE is_depleted = 0 AND quantity_onhand > 0 + ) + GROUP BY h.herb_item_id + HAVING tag_count > 1 + ORDER BY tag_count DESC + LIMIT 5 + """) + + multi_tags = cursor.fetchall() + + if multi_tags: + print(" 여러 효능 태그를 가진 약재:") + for herb in multi_tags: + print(f" - {herb['herb_name']}: {herb['tag_count']}개 태그") + + # 5. 특정 약재 상세 분석 (휴먼감초) + print("\n5. 휴먼감초 상세 분석") + print("-" * 60) + + # 정상 계산 + cursor.execute(""" + SELECT + il.lot_id, + il.quantity_onhand, + il.unit_price_per_g, + il.quantity_onhand * il.unit_price_per_g as value + FROM inventory_lots il + JOIN herb_items h ON il.herb_item_id = h.herb_item_id + WHERE h.herb_name = '휴먼감초' AND il.is_depleted = 0 + """) + + gamcho_lots = cursor.fetchall() + actual_total = sum(lot['value'] for lot in gamcho_lots) + + print(f" 실제 LOT 수: {len(gamcho_lots)}개") + for lot in gamcho_lots: + print(f" LOT {lot['lot_id']}: {lot['quantity_onhand']}g × ₩{lot['unit_price_per_g']} = ₩{lot['value']:,.0f}") + print(f" 실제 합계: ₩{actual_total:,.0f}") + + # JOIN 포함 계산 + cursor.execute(""" + SELECT COUNT(*) as join_rows + FROM herb_items h + LEFT JOIN inventory_lots il ON h.herb_item_id = il.herb_item_id AND il.is_depleted = 0 + LEFT JOIN herb_products hp ON h.insurance_code = hp.product_code + LEFT JOIN herb_item_tags hit ON COALESCE(h.ingredient_code, hp.ingredient_code) = hit.ingredient_code + LEFT JOIN herb_efficacy_tags et ON hit.tag_id = et.tag_id + WHERE h.herb_name = '휴먼감초' AND il.lot_id IS NOT NULL + """) + + join_rows = cursor.fetchone()['join_rows'] + print(f"\n JOIN 후 행 수: {join_rows}행") + + if join_rows > len(gamcho_lots): + print(f" ⚠️ 중복 발생! {join_rows / len(gamcho_lots):.1f}배로 뻥튀기됨") + + conn.close() + +if __name__ == "__main__": + find_duplicate_issue() \ No newline at end of file diff --git a/get_ingredient_codes.py b/get_ingredient_codes.py new file mode 100644 index 0000000..99c3154 --- /dev/null +++ b/get_ingredient_codes.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""데이터베이스에서 실제 ingredient_code 확인""" + +import sqlite3 + +conn = sqlite3.connect('database/kdrug.db') +cur = conn.cursor() + +# herb_items와 herb_products를 조인하여 ingredient_code 확인 +cur.execute(""" + SELECT DISTINCT + hi.herb_name, + COALESCE(hi.ingredient_code, hp.ingredient_code) as ingredient_code, + hi.insurance_code + FROM herb_items hi + LEFT JOIN herb_products hp ON hi.insurance_code = hp.product_code + WHERE COALESCE(hi.ingredient_code, hp.ingredient_code) IS NOT NULL + ORDER BY hi.herb_name +""") + +print("=== 실제 약재 ingredient_code 목록 ===") +herbs = cur.fetchall() +for herb in herbs: + print(f"{herb[0]:10s} -> {herb[1]} (보험코드: {herb[2]})") + +# 십전대보탕 구성 약재들 확인 +target_herbs = ['인삼', '백출', '복령', '감초', '숙지황', '작약', '천궁', '당귀', '황기', '육계'] +print(f"\n=== 십전대보탕 구성 약재 ({len(target_herbs)}개) ===") +for target in target_herbs: + cur.execute(""" + SELECT hi.herb_name, + COALESCE(hi.ingredient_code, hp.ingredient_code) as code + FROM herb_items hi + LEFT JOIN herb_products hp ON hi.insurance_code = hp.product_code + WHERE hi.herb_name = ? + """, (target,)) + result = cur.fetchone() + if result and result[1]: + print(f"✓ {result[0]:6s} -> {result[1]}") + else: + print(f"✗ {target:6s} -> ingredient_code 없음") + +conn.close() \ No newline at end of file diff --git a/migrations/add_herb_extended_info_tables.py b/migrations/add_herb_extended_info_tables.py index 21aa3fa..a5d2495 100644 --- a/migrations/add_herb_extended_info_tables.py +++ b/migrations/add_herb_extended_info_tables.py @@ -245,7 +245,7 @@ def create_disease_herb_mapping(): recommendation_grade VARCHAR(10), -- 권고등급 clinical_notes TEXT, - references TEXT, + reference_sources TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) diff --git a/sample/자산관련.md b/sample/자산관련.md new file mode 100644 index 0000000..280ef50 --- /dev/null +++ b/sample/자산관련.md @@ -0,0 +1,55 @@ +Traceback (most recent call last): + File "/root/kdrug/analyze_inventory_full.py", line 315, in + analyze_inventory_discrepancy() + File "/root/kdrug/analyze_inventory_full.py", line 261, in analyze_inventory_discrepancy + cursor.execute(""" +sqlite3.OperationalError: no such column: quantity + +================================================================================ +재고 자산 금액 불일치 상세 분석 +분석 시간: 2026-02-18 01:23:14 +================================================================================ + +1. 현재 시스템 재고 자산 (inventory_lots 테이블) +------------------------------------------------------------ + 💰 총 재고 자산: ₩1,529,434 + 📦 활성 LOT 수: 30개 + ⚖️ 총 재고량: 86,420.0g + 🌿 약재 종류: 28종 + +2. 입고장 데이터 분석 (purchase_receipts + purchase_receipt_lines) +------------------------------------------------------------ + 📋 총 입고 금액: ₩1,551,900 + 📑 입고장 수: 1건 + 📝 입고 라인 수: 29개 + ⚖️ 총 입고량: 88,000.0g + + 최근 입고장 5건: + - PR-20260211-0001 (20260211): ₩1,551,900 + +3. LOT-입고장 매칭 분석 +------------------------------------------------------------ + ✅ 입고장과 연결된 LOT: 30개 (₩1,529,434) + ❌ 입고장 없는 LOT: 0개 (₩0) + +4. 입고장 라인별 LOT 생성 확인 +------------------------------------------------------------ + 📝 전체 입고 라인: 30개 + ✅ LOT 생성된 라인: 30개 + ❌ LOT 없는 라인: 0개 + +5. 재고 자산 차이 분석 +------------------------------------------------------------ + 💰 현재 LOT 재고 가치: ₩1,529,434 + 📋 원본 입고 금액: ₩1,616,400 + 📊 차이: ₩-86,966 + +6. 출고 및 소비 내역 +------------------------------------------------------------ + 처방전 테이블이 없습니다. + 🏭 복합제 소비 금액: ₩77,966 + ⚖️ 복합제 소비량: 4,580.0g + 📦 복합제 수: 8개 + +7. 재고 보정 내역 +------------------------------------------------------------ \ No newline at end of file diff --git a/direct_test.png b/screenshots/direct_test.png similarity index 100% rename from direct_test.png rename to screenshots/direct_test.png diff --git a/screenshots/herb_info_error.png b/screenshots/herb_info_error.png new file mode 100644 index 0000000..910b992 Binary files /dev/null and b/screenshots/herb_info_error.png differ diff --git a/screenshots/herb_info_page.png b/screenshots/herb_info_page.png new file mode 100644 index 0000000..e076056 Binary files /dev/null and b/screenshots/herb_info_page.png differ diff --git a/purchase_test.png b/screenshots/purchase_test.png similarity index 100% rename from purchase_test.png rename to screenshots/purchase_test.png diff --git a/static/app.js.backup b/static/app.js.backup new file mode 100644 index 0000000..a2879b3 --- /dev/null +++ b/static/app.js.backup @@ -0,0 +1,3172 @@ +// 한약 재고관리 시스템 - Frontend JavaScript + +// 원래 처방 구성 저장용 전역 변수 +let originalFormulaIngredients = {}; + +// 로트 배분 관련 전역 변수 +let currentLotAllocation = { + herbId: null, + requiredQty: 0, + row: null, + data: null +}; + +// 재고 계산 모드 (localStorage에 저장) +let inventoryCalculationMode = localStorage.getItem('inventoryMode') || 'all'; + +$(document).ready(function() { + // 페이지 네비게이션 + $('.sidebar .nav-link').on('click', function(e) { + e.preventDefault(); + const page = $(this).data('page'); + + // Active 상태 변경 + $('.sidebar .nav-link').removeClass('active'); + $(this).addClass('active'); + + // 페이지 전환 + $('.main-content').removeClass('active'); + $(`#${page}`).addClass('active'); + + // 페이지별 데이터 로드 + loadPageData(page); + }); + + // 초기 데이터 로드 + loadPageData('dashboard'); + + // 페이지별 데이터 로드 함수 + function loadPageData(page) { + switch(page) { + case 'dashboard': + loadDashboard(); + break; + case 'patients': + loadPatients(); + break; + case 'purchase': + loadPurchaseReceipts(); + loadSuppliersForSelect(); + break; + case 'formulas': + loadFormulas(); + break; + case 'compound': + loadCompounds(); + loadPatientsForSelect(); + loadFormulasForSelect(); + break; + case 'inventory': + loadInventory(); + break; + case 'herbs': + loadHerbs(); + break; + case 'herb-info': + loadHerbInfo(); + break; + } + } + + // 대시보드 데이터 로드 + function loadDashboard() { + // 환자 수 + $.get('/api/patients', function(response) { + if (response.success) { + $('#totalPatients').text(response.data.length); + } + }); + + // 재고 현황 (저장된 모드 사용) + loadInventorySummary(); + + // 오늘 조제 수 및 최근 조제 내역 + $.get('/api/compounds', function(response) { + if (response.success) { + const today = new Date().toISOString().split('T')[0]; + const todayCompounds = response.data.filter(c => c.compound_date === today); + $('#todayCompounds').text(todayCompounds.length); + + // 최근 조제 내역 (최근 5개) + const tbody = $('#recentCompounds'); + tbody.empty(); + + const recentCompounds = response.data.slice(0, 5); + if (recentCompounds.length > 0) { + recentCompounds.forEach(compound => { + let statusBadge = ''; + switch(compound.status) { + case 'PREPARED': + statusBadge = '조제완료'; + break; + case 'DISPENSED': + statusBadge = '출고완료'; + break; + case 'CANCELLED': + statusBadge = '취소'; + break; + default: + statusBadge = '대기'; + } + + tbody.append(` + + ${compound.compound_date || '-'} + ${compound.patient_name || '직접조제'} + ${compound.formula_name || '직접조제'} + ${compound.je_count}제 + ${compound.pouch_total}개 + ${statusBadge} + + `); + }); + } else { + tbody.html('조제 내역이 없습니다.'); + } + } + }); + } + + // 환자 목록 로드 + function loadPatients() { + $.get('/api/patients', function(response) { + if (response.success) { + const tbody = $('#patientsList'); + tbody.empty(); + + // 각 환자의 처방 횟수를 가져오기 위해 처방 데이터도 로드 + $.get('/api/compounds', function(compoundsResponse) { + const compounds = compoundsResponse.success ? compoundsResponse.data : []; + + // 환자별 처방 횟수 계산 + const compoundCounts = {}; + compounds.forEach(compound => { + if (compound.patient_id) { + compoundCounts[compound.patient_id] = (compoundCounts[compound.patient_id] || 0) + 1; + } + }); + + response.data.forEach(patient => { + const compoundCount = compoundCounts[patient.patient_id] || 0; + + tbody.append(` + + ${patient.name} + ${patient.phone} + ${patient.gender === 'M' ? '남' : patient.gender === 'F' ? '여' : '-'} + ${patient.birth_date || '-'} + + ${compoundCount}회 + + ${patient.notes || '-'} + + + + + + `); + }); + + // 처방내역 버튼 이벤트 + $('.view-patient-compounds').on('click', function() { + const patientId = $(this).data('id'); + const patientName = $(this).data('name'); + viewPatientCompounds(patientId, patientName); + }); + }); + } + }); + } + + // 환자 등록 + $('#savePatientBtn').on('click', function() { + const patientData = { + name: $('#patientName').val(), + phone: $('#patientPhone').val(), + jumin_no: $('#patientJumin').val(), + gender: $('#patientGender').val(), + birth_date: $('#patientBirth').val(), + address: $('#patientAddress').val(), + notes: $('#patientNotes').val() + }; + + $.ajax({ + url: '/api/patients', + method: 'POST', + contentType: 'application/json', + data: JSON.stringify(patientData), + success: function(response) { + if (response.success) { + alert('환자가 등록되었습니다.'); + $('#patientModal').modal('hide'); + $('#patientForm')[0].reset(); + loadPatients(); + } + }, + error: function(xhr) { + alert('오류: ' + xhr.responseJSON.error); + } + }); + }); + + // 환자 처방 내역 조회 + function viewPatientCompounds(patientId, patientName) { + // 환자 정보 가져오기 + $.get(`/api/patients/${patientId}`, function(patientResponse) { + if (patientResponse.success) { + const patient = patientResponse.data; + + // 환자 기본 정보 표시 + $('#patientCompoundsName').text(patient.name); + $('#patientInfoName').text(patient.name); + $('#patientInfoPhone').text(patient.phone || '-'); + $('#patientInfoGender').text(patient.gender === 'M' ? '남성' : patient.gender === 'F' ? '여성' : '-'); + $('#patientInfoBirth').text(patient.birth_date || '-'); + + // 환자의 처방 내역 가져오기 + $.get(`/api/patients/${patientId}/compounds`, function(compoundsResponse) { + if (compoundsResponse.success) { + const compounds = compoundsResponse.compounds || []; + + // 통계 계산 + const totalCompounds = compounds.length; + let totalJe = 0; + let totalAmount = 0; + let lastVisit = '-'; + + if (compounds.length > 0) { + compounds.forEach(c => { + totalJe += c.je_count || 0; + totalAmount += c.sell_price_total || 0; + }); + lastVisit = compounds[0].compound_date || '-'; + } + + // 통계 표시 + $('#patientTotalCompounds').text(totalCompounds + '회'); + $('#patientLastVisit').text(lastVisit); + $('#patientTotalJe').text(totalJe + '제'); + $('#patientTotalAmount').text(formatCurrency(totalAmount)); + + // 처방 내역 테이블 표시 + const tbody = $('#patientCompoundsList'); + tbody.empty(); + + if (compounds.length === 0) { + tbody.append(` + + 처방 내역이 없습니다. + + `); + } else { + compounds.forEach((compound, index) => { + // 상태 뱃지 + let statusBadge = ''; + switch(compound.status) { + case 'PREPARED': + statusBadge = '조제완료'; + break; + case 'DISPENSED': + statusBadge = '출고완료'; + break; + case 'CANCELLED': + statusBadge = '취소'; + break; + default: + statusBadge = '대기'; + } + + const detailRowId = `compound-detail-${compound.compound_id}`; + + // 처방명 표시 (가감방 여부 포함) + let formulaDisplay = compound.formula_name || '직접조제'; + if (compound.is_custom && compound.formula_name) { + formulaDisplay = `${compound.formula_name} 가감`; + } + + tbody.append(` + + + + + ${compound.compound_date || '-'} + + ${formulaDisplay} + ${compound.custom_summary ? `
${compound.custom_summary}` : ''} + + ${compound.je_count || 0} + ${compound.cheop_total || 0} + ${compound.pouch_total || 0} + ${formatCurrency(compound.cost_total || 0)} + ${formatCurrency(compound.sell_price_total || 0)} + ${statusBadge} + ${compound.prescription_no || '-'} + + + +
+
+
+
+
구성 약재
+
+
+
+ 로딩 중... +
+
+ +
재고 소비 내역
+
+
+
+ 로딩 중... +
+
+
+
+
+
+ + + `); + }); + + // 행 클릭 이벤트 - 상세 정보 토글 + $('.compound-row').on('click', function() { + const compoundId = $(this).data('compound-id'); + const detailRow = $(`#compound-detail-${compoundId}`); + const icon = $(this).find('.toggle-icon'); + + if (detailRow.is(':visible')) { + // 닫기 + detailRow.slideUp(); + icon.removeClass('bi-chevron-down').addClass('bi-chevron-right'); + } else { + // 열기 - 다른 모든 행 닫기 + $('.collapse-row').slideUp(); + $('.toggle-icon').removeClass('bi-chevron-down').addClass('bi-chevron-right'); + + // 현재 행 열기 + detailRow.slideDown(); + icon.removeClass('bi-chevron-right').addClass('bi-chevron-down'); + + // 상세 정보 로드 + loadCompoundDetailInline(compoundId); + } + }); + } + + // 모달 표시 + $('#patientCompoundsModal').modal('show'); + } + }).fail(function() { + alert('처방 내역을 불러오는데 실패했습니다.'); + }); + } + }).fail(function() { + alert('환자 정보를 불러오는데 실패했습니다.'); + }); + } + + // 환자 처방 내역 모달 내에서 조제 상세 정보 로드 (인라인) + function loadCompoundDetailInline(compoundId) { + $.get(`/api/compounds/${compoundId}`, function(response) { + if (response.success && response.data) { + const data = response.data; + + // 구성 약재 테이블 + let ingredientsHtml = ''; + + if (data.ingredients && data.ingredients.length > 0) { + data.ingredients.forEach(ing => { + ingredientsHtml += ` + + + + + + + `; + }); + } else { + ingredientsHtml += ''; + } + ingredientsHtml += '
약재명보험코드첩당용량총용량
${ing.herb_name}${ing.insurance_code || '-'}${ing.grams_per_cheop}g${ing.total_grams}g
약재 정보가 없습니다
'; + + $(`#ingredients-${compoundId}`).html(ingredientsHtml); + + // 재고 소비 내역 테이블 + let consumptionsHtml = ''; + + if (data.consumptions && data.consumptions.length > 0) { + let totalCost = 0; + data.consumptions.forEach(con => { + totalCost += con.cost_amount || 0; + consumptionsHtml += ` + + + + + + + + + `; + }); + consumptionsHtml += ` + + + + + `; + } else { + consumptionsHtml += ''; + } + consumptionsHtml += '
약재명원산지도매상사용량단가원가
${con.herb_name}${con.origin_country || '-'}${con.supplier_name || '-'}${con.quantity_used}g${formatCurrency(con.unit_cost_per_g)}/g${formatCurrency(con.cost_amount)}
총 원가:${formatCurrency(totalCost)}
재고 소비 내역이 없습니다
'; + + $(`#consumptions-${compoundId}`).html(consumptionsHtml); + } + }).fail(function() { + $(`#ingredients-${compoundId}`).html('
데이터를 불러오는데 실패했습니다.
'); + $(`#consumptions-${compoundId}`).html('
데이터를 불러오는데 실패했습니다.
'); + }); + } + + // 처방 목록 로드 + function loadFormulas() { + $.get('/api/formulas', function(response) { + if (response.success) { + const tbody = $('#formulasList'); + tbody.empty(); + + response.data.forEach(formula => { + tbody.append(` + + ${formula.formula_code || '-'} + ${formula.formula_name} + ${formula.base_cheop}첩 + ${formula.base_pouches}파우치 + + + + + + + + `); + }); + + // 구성 약재 보기 + $('.view-ingredients').on('click', function() { + const formulaId = $(this).data('id'); + $.get(`/api/formulas/${formulaId}/ingredients`, function(response) { + if (response.success) { + let ingredientsList = response.data.map(ing => + `${ing.herb_name}: ${ing.grams_per_cheop}g` + ).join(', '); + alert('구성 약재:\n' + ingredientsList); + } + }); + }); + } + }); + } + + // 처방 구성 약재 추가 (모달) + let formulaIngredientCount = 0; + $('#addFormulaIngredientBtn').on('click', function() { + formulaIngredientCount++; + $('#formulaIngredients').append(` + + + + + + + + + + + + + + + `); + + // 약재 목록 로드 + const selectElement = $(`#formulaIngredients tr[data-row="${formulaIngredientCount}"] .herb-select`); + loadHerbsForSelect(selectElement); + + // 삭제 버튼 이벤트 + $(`#formulaIngredients tr[data-row="${formulaIngredientCount}"] .remove-ingredient`).on('click', function() { + $(this).closest('tr').remove(); + }); + }); + + // 처방 저장 + $('#saveFormulaBtn').on('click', function() { + const ingredients = []; + $('#formulaIngredients tr').each(function() { + const herbId = $(this).find('.herb-select').val(); + const grams = $(this).find('.grams-input').val(); + + if (herbId && grams) { + ingredients.push({ + herb_item_id: parseInt(herbId), + grams_per_cheop: parseFloat(grams), + notes: $(this).find('.notes-input').val() + }); + } + }); + + const formulaData = { + formula_code: $('#formulaCode').val(), + formula_name: $('#formulaName').val(), + formula_type: $('#formulaType').val(), + base_cheop: parseInt($('#baseCheop').val()), + base_pouches: parseInt($('#basePouches').val()), + description: $('#formulaDescription').val(), + ingredients: ingredients + }; + + $.ajax({ + url: '/api/formulas', + method: 'POST', + contentType: 'application/json', + data: JSON.stringify(formulaData), + success: function(response) { + if (response.success) { + alert('처방이 등록되었습니다.'); + $('#formulaModal').modal('hide'); + $('#formulaForm')[0].reset(); + $('#formulaIngredients').empty(); + loadFormulas(); + } + }, + error: function(xhr) { + alert('오류: ' + xhr.responseJSON.error); + } + }); + }); + + // 조제 관리 + $('#newCompoundBtn').on('click', function() { + $('#compoundForm').show(); + $('#compoundEntryForm')[0].reset(); + $('#compoundIngredients').empty(); + }); + + $('#cancelCompoundBtn').on('click', function() { + $('#compoundForm').hide(); + }); + + // 제수 변경 시 첩수 자동 계산 + $('#jeCount').on('input', function() { + const jeCount = parseFloat($(this).val()) || 0; + const cheopTotal = jeCount * 20; + const pouchTotal = jeCount * 30; + + $('#cheopTotal').val(cheopTotal); + $('#pouchTotal').val(pouchTotal); + + // 약재별 총 용량 재계산 + updateIngredientTotals(); + }); + + // 처방 선택 시 구성 약재 로드 + $('#compoundFormula').on('change', function() { + const formulaId = $(this).val(); + + // 원래 처방 구성 초기화 + originalFormulaIngredients = {}; + $('#customPrescriptionBadge').remove(); // 커스텀 뱃지 제거 + + if (!formulaId) { + $('#compoundIngredients').empty(); + return; + } + + // 직접조제인 경우 + if (formulaId === 'custom') { + $('#compoundIngredients').empty(); + // 빈 행 하나 추가 + addEmptyIngredientRow(); + return; + } + + // 등록된 처방인 경우 + $.get(`/api/formulas/${formulaId}/ingredients`, function(response) { + if (response.success) { + $('#compoundIngredients').empty(); + + // 원래 처방 구성 저장 + response.data.forEach(ing => { + originalFormulaIngredients[ing.ingredient_code] = { + herb_name: ing.herb_name, + grams_per_cheop: ing.grams_per_cheop + }; + }); + + response.data.forEach(ing => { + const cheopTotal = parseFloat($('#cheopTotal').val()) || 0; + const totalGrams = ing.grams_per_cheop * cheopTotal; + + // 제품 선택 옵션 생성 + let productOptions = ''; + if (ing.available_products && ing.available_products.length > 0) { + ing.available_products.forEach(product => { + const specInfo = product.specification ? ` [${product.specification}]` : ''; + productOptions += ``; + }); + } + + $('#compoundIngredients').append(` + + + ${ing.herb_name} + ${ing.total_available_stock > 0 + ? `(총 ${ing.total_available_stock.toFixed(0)}g 사용 가능)` + : '(재고 없음)'} + + + + + ${totalGrams.toFixed(1)} + +
+ + +
+ + 대기중 + + + + + `); + + // 첫 번째 제품 자동 선택 및 원산지 로드 + const tr = $(`tr[data-ingredient-code="${ing.ingredient_code}"]`); + if (ing.available_products && ing.available_products.length > 0) { + const firstProduct = ing.available_products[0]; + tr.find('.product-select').val(firstProduct.herb_item_id); + tr.attr('data-herb-id', firstProduct.herb_item_id); + // 원산지/로트 옵션 로드 + loadOriginOptions(firstProduct.herb_item_id, totalGrams); + } + }); + + // 재고 확인 + checkStockForCompound(); + + // 제품 선택 변경 이벤트 + $('.product-select').on('change', function() { + const herbId = $(this).val(); + const row = $(this).closest('tr'); + + if (herbId) { + row.attr('data-herb-id', herbId); + const cheopTotal = parseFloat($('#cheopTotal').val()) || 0; + const gramsPerCheop = parseFloat(row.find('.grams-per-cheop').val()) || 0; + const totalGrams = gramsPerCheop * cheopTotal; + + // 원산지/로트 옵션 로드 + loadOriginOptions(herbId, totalGrams); + } else { + row.attr('data-herb-id', ''); + row.find('.origin-select').empty().append('').prop('disabled', true); + row.find('.stock-status').text('대기중'); + } + }); + + // 용량 변경 이벤트 + $('.grams-per-cheop').on('input', function() { + updateIngredientTotals(); + + // 원산지 옵션 다시 로드 + const row = $(this).closest('tr'); + const herbId = row.attr('data-herb-id'); + if (herbId) { + const cheopTotal = parseFloat($('#cheopTotal').val()) || 0; + const gramsPerCheop = parseFloat($(this).val()) || 0; + const totalGrams = gramsPerCheop * cheopTotal; + loadOriginOptions(herbId, totalGrams); + } + }); + + // 삭제 버튼 이벤트 + $('.remove-compound-ingredient').on('click', function() { + $(this).closest('tr').remove(); + updateIngredientTotals(); // 총용량 재계산 및 커스텀 감지 + }); + } + }); + }); + + // 약재별 총 용량 업데이트 + function updateIngredientTotals() { + const cheopTotal = parseFloat($('#cheopTotal').val()) || 0; + + $('#compoundIngredients tr').each(function() { + const gramsPerCheop = parseFloat($(this).find('.grams-per-cheop').val()) || 0; + const totalGrams = gramsPerCheop * cheopTotal; + $(this).find('.total-grams').text(totalGrams.toFixed(1)); + }); + + checkStockForCompound(); + // 커스텀 처방 감지 호출 + checkCustomPrescription(); + } + + // 커스텀 처방 감지 함수 + function checkCustomPrescription() { + const formulaId = $('#compoundFormula').val(); + + // 처방이 선택되지 않았거나 직접조제인 경우 리턴 + if (!formulaId || formulaId === 'custom' || Object.keys(originalFormulaIngredients).length === 0) { + $('#customPrescriptionBadge').remove(); + return; + } + + // 현재 약재 구성 수집 + const currentIngredients = {}; + $('#compoundIngredients tr').each(function() { + const ingredientCode = $(this).attr('data-ingredient-code'); + const gramsPerCheop = parseFloat($(this).find('.grams-per-cheop').val()); + + if (ingredientCode && gramsPerCheop > 0) { + currentIngredients[ingredientCode] = gramsPerCheop; + } + }); + + // 변경사항 감지 + const customDetails = []; + let isCustom = false; + + // 추가된 약재 확인 + for (const code in currentIngredients) { + if (!originalFormulaIngredients[code]) { + const herbName = $(`tr[data-ingredient-code="${code}"] .herb-select-compound option:selected`).data('herb-name') || code; + customDetails.push(`${herbName} ${currentIngredients[code]}g 추가`); + isCustom = true; + } + } + + // 삭제된 약재 확인 + for (const code in originalFormulaIngredients) { + if (!currentIngredients[code]) { + customDetails.push(`${originalFormulaIngredients[code].herb_name} 제거`); + isCustom = true; + } + } + + // 용량 변경된 약재 확인 + for (const code in currentIngredients) { + if (originalFormulaIngredients[code]) { + const originalGrams = originalFormulaIngredients[code].grams_per_cheop; + const currentGrams = currentIngredients[code]; + + if (Math.abs(originalGrams - currentGrams) > 0.01) { + const herbName = originalFormulaIngredients[code].herb_name; + customDetails.push(`${herbName} ${originalGrams}g→${currentGrams}g`); + isCustom = true; + } + } + } + + // 커스텀 뱃지 표시/숨기기 + $('#customPrescriptionBadge').remove(); + + if (isCustom) { + const badgeHtml = ` +
+ 가감방 + ${customDetails.join(' | ')} +
+ `; + + // 처방 선택 영역 아래에 추가 + $('#compoundFormula').closest('.col-md-6').append(badgeHtml); + } + } + + // 재고 확인 + function checkStockForCompound() { + $('#compoundIngredients tr').each(function() { + const herbId = $(this).data('herb-id'); + const totalGrams = parseFloat($(this).find('.total-grams').text()) || 0; + const $stockStatus = $(this).find('.stock-status'); + + // TODO: API 호출로 실제 재고 확인 + $stockStatus.text('재고 확인 필요'); + }); + } + + // 조제 약재 추가 + // 빈 약재 행 추가 함수 + function addEmptyIngredientRow() { + const newRow = $(` + + + + + + + + 0.0 + +
+ + +
+ + - + + + + + `); + + $('#compoundIngredients').append(newRow); + + // 약재 목록 로드 + const herbSelect = newRow.find('.herb-select-compound'); + loadHerbsForSelect(herbSelect); + + // 약재(마스터) 선택 시 제품 옵션 로드 + newRow.find('.herb-select-compound').on('change', function() { + const ingredientCode = $(this).val(); + const herbName = $(this).find('option:selected').data('herb-name'); + if (ingredientCode) { + const row = $(this).closest('tr'); + row.attr('data-ingredient-code', ingredientCode); + + // 제품 목록 로드 + loadProductOptions(row, ingredientCode, herbName); + + // 제품 선택 활성화 + row.find('.product-select').prop('disabled', false); + + // 원산지 선택 초기화 및 비활성화 + row.find('.origin-select').empty().append('').prop('disabled', true); + } else { + const row = $(this).closest('tr'); + row.attr('data-ingredient-code', ''); + row.attr('data-herb-id', ''); + row.find('.product-select').empty().append('').prop('disabled', true); + row.find('.origin-select').empty().append('').prop('disabled', true); + } + }); + + // 제품 선택 이벤트 + newRow.find('.product-select').on('change', function() { + const herbId = $(this).val(); + const row = $(this).closest('tr'); + + if (herbId) { + row.attr('data-herb-id', herbId); + + // 원산지 선택 활성화 + row.find('.origin-select').prop('disabled', false); + + // 원산지 옵션 로드 + const cheopTotal = parseFloat($('#cheopTotal').val()) || 0; + const gramsPerCheop = parseFloat(row.find('.grams-per-cheop').val()) || 0; + const totalGrams = gramsPerCheop * cheopTotal; + loadOriginOptions(herbId, totalGrams); + } else { + row.attr('data-herb-id', ''); + row.find('.origin-select').empty().append('').prop('disabled', true); + } + }); + + // 이벤트 바인딩 + newRow.find('.grams-per-cheop').on('input', function() { + updateIngredientTotals(); + // 원산지 옵션 다시 로드 + const herbId = $(this).closest('tr').attr('data-herb-id'); + if (herbId) { + const cheopTotal = parseFloat($('#cheopTotal').val()) || 0; + const gramsPerCheop = parseFloat($(this).val()) || 0; + const totalGrams = gramsPerCheop * cheopTotal; + loadOriginOptions(herbId, totalGrams); + } + }); + + newRow.find('.remove-compound-ingredient').on('click', function() { + $(this).closest('tr').remove(); + updateIngredientTotals(); + }); + } + + $('#addIngredientBtn').on('click', function() { + addEmptyIngredientRow(); + }); + + // 기존 약재 추가 버튼 (기존 코드 삭제) + /* + $('#addIngredientBtn').on('click', function() { + const newRow = $(` + + + + + + + + 0.0 + - + + + + + `); + + $('#compoundIngredients').append(newRow); + + // 약재 목록 로드 + loadHerbsForSelect(newRow.find('.herb-select-compound')); + + // 이벤트 바인딩 + newRow.find('.grams-per-cheop').on('input', updateIngredientTotals); + newRow.find('.remove-compound-ingredient').on('click', function() { + $(this).closest('tr').remove(); + updateIngredientTotals(); // 총용량 재계산 및 커스텀 감지 + }); + newRow.find('.herb-select-compound').on('change', function() { + const herbId = $(this).val(); + $(this).closest('tr').attr('data-herb-id', herbId); + updateIngredientTotals(); + }); + }); + */ + + // 조제 실행 + $('#compoundEntryForm').on('submit', function(e) { + e.preventDefault(); + + // getIngredientDataForCompound 함수 사용하여 lot_assignments 포함 + const ingredients = getIngredientDataForCompound(); + + const compoundData = { + patient_id: $('#compoundPatient').val() ? parseInt($('#compoundPatient').val()) : null, + formula_id: $('#compoundFormula').val() ? parseInt($('#compoundFormula').val()) : null, + je_count: parseFloat($('#jeCount').val()), + cheop_total: parseFloat($('#cheopTotal').val()), + pouch_total: parseFloat($('#pouchTotal').val()), + ingredients: ingredients + }; + + $.ajax({ + url: '/api/compounds', + method: 'POST', + contentType: 'application/json', + data: JSON.stringify(compoundData), + success: function(response) { + if (response.success) { + alert(`조제가 완료되었습니다.\n원가: ${formatCurrency(response.total_cost)}`); + $('#compoundForm').hide(); + loadCompounds(); + } + }, + error: function(xhr) { + alert('오류: ' + xhr.responseJSON.error); + } + }); + }); + + // 조제 내역 로드 + function loadCompounds() { + $.get('/api/compounds', function(response) { + const tbody = $('#compoundsList'); + tbody.empty(); + + if (response.success && response.data.length > 0) { + // 통계 업데이트 + const today = new Date().toISOString().split('T')[0]; + const currentMonth = new Date().toISOString().slice(0, 7); + + let todayCount = 0; + let monthCount = 0; + + response.data.forEach((compound, index) => { + // 통계 계산 + if (compound.compound_date === today) todayCount++; + if (compound.compound_date && compound.compound_date.startsWith(currentMonth)) monthCount++; + + // 상태 뱃지 + let statusBadge = ''; + switch(compound.status) { + case 'PREPARED': + statusBadge = '조제완료'; + break; + case 'DISPENSED': + statusBadge = '출고완료'; + break; + case 'CANCELLED': + statusBadge = '취소'; + break; + default: + statusBadge = '대기'; + } + + const row = $(` + + ${response.data.length - index} + ${compound.compound_date || ''}
${compound.created_at ? compound.created_at.split(' ')[1] : ''} + ${compound.patient_name || '직접조제'} + ${compound.patient_phone || '-'} + ${compound.formula_name || '직접조제'} + ${compound.je_count || 0} + ${compound.cheop_total || 0} + ${compound.pouch_total || 0} + ${formatCurrency(compound.cost_total || 0)} + ${formatCurrency(compound.sell_price_total || 0)} + ${statusBadge} + ${compound.prescription_no || '-'} + + + + + `); + tbody.append(row); + }); + + // 통계 업데이트 + $('#todayCompoundCount').text(todayCount); + $('#monthCompoundCount').text(monthCount); + + // 상세보기 버튼 이벤트 + $('.view-compound-detail').on('click', function() { + const compoundId = $(this).data('id'); + viewCompoundDetail(compoundId); + }); + } else { + tbody.html('조제 내역이 없습니다.'); + $('#todayCompoundCount').text(0); + $('#monthCompoundCount').text(0); + } + }).fail(function() { + $('#compoundsList').html('데이터를 불러오는데 실패했습니다.'); + }); + } + + // 조제 상세보기 + function viewCompoundDetail(compoundId) { + $.get(`/api/compounds/${compoundId}`, function(response) { + if (response.success && response.data) { + const data = response.data; + + // 환자 정보 + $('#detailPatientName').text(data.patient_name || '직접조제'); + $('#detailPatientPhone').text(data.patient_phone || '-'); + $('#detailCompoundDate').text(data.compound_date || '-'); + + // 처방 정보 (가감방 표시 포함) + let formulaDisplay = data.formula_name || '직접조제'; + if (data.is_custom && data.formula_name) { + formulaDisplay += ' 가감'; + if (data.custom_summary) { + formulaDisplay += `
${data.custom_summary}`; + } + } + $('#detailFormulaName').html(formulaDisplay); // text() 대신 html() 사용 + $('#detailPrescriptionNo').text(data.prescription_no || '-'); + $('#detailQuantities').text(`${data.je_count}제 / ${data.cheop_total}첩 / ${data.pouch_total}파우치`); + + // 처방 구성 약재 + const ingredientsBody = $('#detailIngredients'); + ingredientsBody.empty(); + if (data.ingredients && data.ingredients.length > 0) { + data.ingredients.forEach(ing => { + ingredientsBody.append(` + + ${ing.herb_name} + ${ing.insurance_code || '-'} + ${ing.grams_per_cheop}g + ${ing.total_grams}g + ${ing.notes || '-'} + + `); + }); + } + + // 재고 소비 내역 + const consumptionsBody = $('#detailConsumptions'); + consumptionsBody.empty(); + if (data.consumptions && data.consumptions.length > 0) { + data.consumptions.forEach(con => { + consumptionsBody.append(` + + ${con.herb_name} + ${con.origin_country || '-'} + ${con.supplier_name || '-'} + ${con.quantity_used}g + ${formatCurrency(con.unit_cost_per_g)}/g + ${formatCurrency(con.cost_amount)} + + `); + }); + } + + // 총 원가 + $('#detailTotalCost').text(formatCurrency(data.cost_total || 0)); + + // 비고 + $('#detailNotes').text(data.notes || ''); + + // 부모 모달(환자 처방 내역)을 임시로 숨기고 조제 상세 모달 열기 + const parentModal = $('#patientCompoundsModal'); + const wasParentOpen = parentModal.hasClass('show'); + + if (wasParentOpen) { + // 부모 모달 숨기기 (DOM에서 제거하지 않음) + parentModal.modal('hide'); + + // 조제 상세 모달이 닫힐 때 부모 모달 다시 열기 + $('#compoundDetailModal').off('hidden.bs.modal').on('hidden.bs.modal', function() { + parentModal.modal('show'); + }); + } + + // 조제 상세 모달 열기 + $('#compoundDetailModal').modal('show'); + } + }).fail(function() { + alert('조제 상세 정보를 불러오는데 실패했습니다.'); + }); + } + + // 재고 현황 로드 + function loadInventory() { + $.get('/api/inventory/summary', function(response) { + if (response.success) { + const tbody = $('#inventoryList'); + tbody.empty(); + + let totalValue = 0; + let herbsInStock = 0; + + // 주성분코드 기준 보유 현황 표시 + if (response.summary) { + const summary = response.summary; + const coverageHtml = ` +
+
+
+
📊 급여 약재 보유 현황
+
+
+ 전체 급여 약재: ${summary.total_ingredient_codes || 454}개 주성분 +
+
+ 보유 약재: ${summary.owned_ingredient_codes || 0}개 주성분 +
+
+ 보유율: + ${summary.coverage_rate || 0}% +
+
+
+
+
+
+ ${summary.owned_ingredient_codes || 0} / ${summary.total_ingredient_codes || 454} +
+
+
+
+
+ + ※ 건강보험 급여 한약재 ${summary.total_ingredient_codes || 454}개 주성분 중 ${summary.owned_ingredient_codes || 0}개 보유 + +
+
+ `; + + // 재고 테이블 위에 통계 표시 + if ($('#inventoryCoverage').length === 0) { + $('#inventoryList').parent().before(`
${coverageHtml}
`); + } else { + $('#inventoryCoverage').html(coverageHtml); + } + } + + response.data.forEach(item => { + // 원산지가 여러 개인 경우 표시 + const originBadge = item.origin_count > 1 + ? `${item.origin_count}개 원산지` + : ''; + + // 효능 태그 표시 + let efficacyTags = ''; + if (item.efficacy_tags && item.efficacy_tags.length > 0) { + efficacyTags = item.efficacy_tags.map(tag => + `${tag}` + ).join(''); + } + + // 가격 범위 표시 (원산지가 여러 개이고 가격차가 있는 경우) + let priceDisplay = item.avg_price ? formatCurrency(item.avg_price) : '-'; + if (item.origin_count > 1 && item.min_price && item.max_price && item.min_price !== item.max_price) { + priceDisplay = `${formatCurrency(item.min_price)} ~ ${formatCurrency(item.max_price)}`; + } + + // 통계 업데이트 + totalValue += item.total_value || 0; + if (item.total_quantity > 0) herbsInStock++; + + tbody.append(` + + ${item.insurance_code || '-'} + ${item.herb_name}${originBadge}${efficacyTags} + ${item.total_quantity.toFixed(1)} + ${item.lot_count} + ${priceDisplay} + ${formatCurrency(item.total_value)} + + + + + + `); + }); + + // 통계 업데이트 + $('#totalInventoryValue').text(formatCurrency(totalValue)); + $('#totalHerbsInStock').text(`${herbsInStock}종`); + + // 클릭 이벤트 바인딩 + $('.view-inventory-detail').on('click', function(e) { + e.stopPropagation(); + const herbId = $(this).data('herb-id'); + showInventoryDetail(herbId); + }); + + // 입출고 내역 버튼 이벤트 + $('.view-stock-ledger').on('click', function(e) { + e.stopPropagation(); + const herbId = $(this).data('herb-id'); + const herbName = $(this).data('herb-name'); + viewStockLedger(herbId, herbName); + }); + } + }); + } + + // 재고 상세 모달 표시 + function showInventoryDetail(herbId) { + $.get(`/api/inventory/detail/${herbId}`, function(response) { + if (response.success) { + const data = response.data; + + // 원산지별 재고 정보 HTML 생성 + let originsHtml = ''; + data.origins.forEach(origin => { + originsHtml += ` +
+
+
+ ${origin.origin_country} + ${origin.total_quantity.toFixed(1)}g +
+
+
+
+
+ 평균 단가:
+ ${formatCurrency(origin.avg_price)}/g +
+
+ 재고 가치:
+ ${formatCurrency(origin.total_value)} +
+
+ + + + + + + + + + + + `; + + origin.lots.forEach(lot => { + // variant 속성들을 뱃지로 표시 + let variantBadges = ''; + if (lot.form) variantBadges += `${lot.form}`; + if (lot.processing) variantBadges += `${lot.processing}`; + if (lot.grade) variantBadges += `${lot.grade}`; + + originsHtml += ` + + + + + + + + `; + }); + + originsHtml += ` + +
로트ID품명수량단가입고일도매상
#${lot.lot_id} + ${lot.display_name ? `${lot.display_name}` : '-'} + ${variantBadges} + ${lot.quantity_onhand.toFixed(1)}g${formatCurrency(lot.unit_price_per_g)}${lot.received_date}${lot.supplier_name || '-'}
+
+
`; + }); + + // 모달 생성 및 표시 + const modalHtml = ` + `; + + // 기존 모달 제거 + $('#inventoryDetailModal').remove(); + $('body').append(modalHtml); + + // 모달 표시 + const modal = new bootstrap.Modal(document.getElementById('inventoryDetailModal')); + modal.show(); + } + }); + } + + // 약재 목록 로드 + function loadHerbs() { + $.get('/api/herbs', function(response) { + if (response.success) { + const tbody = $('#herbsList'); + tbody.empty(); + + response.data.forEach(herb => { + tbody.append(` + + ${herb.insurance_code || '-'} + ${herb.herb_name} + ${herb.specification || '-'} + ${herb.current_stock ? herb.current_stock.toFixed(1) + 'g' : '0g'} + + + + + `); + }); + } + }); + } + + // 입고장 목록 로드 + function loadPurchaseReceipts() { + const startDate = $('#purchaseStartDate').val(); + const endDate = $('#purchaseEndDate').val(); + const supplierId = $('#purchaseSupplier').val(); + + let url = '/api/purchase-receipts?'; + if (startDate) url += `start_date=${startDate}&`; + if (endDate) url += `end_date=${endDate}&`; + if (supplierId) url += `supplier_id=${supplierId}`; + + $.get(url, function(response) { + if (response.success) { + const tbody = $('#purchaseReceiptsList'); + tbody.empty(); + + if (response.data.length === 0) { + tbody.append('입고장이 없습니다.'); + return; + } + + response.data.forEach(receipt => { + tbody.append(` + + ${receipt.receipt_date} + ${receipt.supplier_name} + ${receipt.line_count}개 + ${receipt.total_amount ? formatCurrency(receipt.total_amount) : '-'} + ${receipt.total_quantity ? receipt.total_quantity.toLocaleString() + 'g' : '-'} + ${receipt.source_file || '-'} + + + + + + `); + }); + + // 이벤트 바인딩 + $('.view-receipt').on('click', function() { + const receiptId = $(this).data('id'); + viewReceiptDetail(receiptId); + }); + + $('.delete-receipt').on('click', function() { + const receiptId = $(this).data('id'); + if (confirm('정말 이 입고장을 삭제하시겠습니까? 사용되지 않은 재고만 삭제 가능합니다.')) { + deleteReceipt(receiptId); + } + }); + } + }); + } + + // 입고장 상세 보기 + function viewReceiptDetail(receiptId) { + $.get(`/api/purchase-receipts/${receiptId}`, function(response) { + if (response.success) { + const data = response.data; + let linesHtml = ''; + + data.lines.forEach(line => { + // display_name이 있으면 표시, 없으면 herb_name + const displayName = line.display_name || line.herb_name; + + // variant 속성들을 뱃지로 표시 + let variantBadges = ''; + if (line.form) variantBadges += `${line.form}`; + if (line.processing) variantBadges += `${line.processing}`; + if (line.grade) variantBadges += `${line.grade}`; + + linesHtml += ` + + +
${line.herb_name}
+ ${line.display_name ? `${line.display_name}` : ''} + ${variantBadges} + + ${line.insurance_code || '-'} + ${line.origin_country || '-'} + ${line.quantity_g}g + ${formatCurrency(line.unit_price_per_g)} + ${formatCurrency(line.line_total)} + ${line.current_stock}g + + `; + }); + + const modalHtml = ` + + `; + + // 기존 모달 제거 + $('#receiptDetailModal').remove(); + $('body').append(modalHtml); + $('#receiptDetailModal').modal('show'); + } + }); + } + + // 입고장 삭제 + function deleteReceipt(receiptId) { + $.ajax({ + url: `/api/purchase-receipts/${receiptId}`, + method: 'DELETE', + success: function(response) { + if (response.success) { + alert(response.message); + loadPurchaseReceipts(); + } + }, + error: function(xhr) { + alert('오류: ' + xhr.responseJSON.error); + } + }); + } + + // 입고장 조회 버튼 + $('#searchPurchaseBtn').on('click', function() { + loadPurchaseReceipts(); + }); + + // 도매상 목록 로드 (셀렉트 박스용) + function loadSuppliersForSelect() { + $.get('/api/suppliers', function(response) { + if (response.success) { + const select = $('#uploadSupplier'); + select.empty().append(''); + + response.data.forEach(supplier => { + select.append(``); + }); + + // 필터용 셀렉트 박스도 업데이트 + const filterSelect = $('#purchaseSupplier'); + filterSelect.empty().append(''); + response.data.forEach(supplier => { + filterSelect.append(``); + }); + } + }); + } + + // 도매상 등록 + $('#saveSupplierBtn').on('click', function() { + const supplierData = { + name: $('#supplierName').val(), + business_no: $('#supplierBusinessNo').val(), + contact_person: $('#supplierContactPerson').val(), + phone: $('#supplierPhone').val(), + address: $('#supplierAddress').val() + }; + + if (!supplierData.name) { + alert('도매상명은 필수입니다.'); + return; + } + + $.ajax({ + url: '/api/suppliers', + method: 'POST', + contentType: 'application/json', + data: JSON.stringify(supplierData), + success: function(response) { + if (response.success) { + alert('도매상이 등록되었습니다.'); + $('#supplierModal').modal('hide'); + $('#supplierForm')[0].reset(); + loadSuppliersForSelect(); + } + }, + error: function(xhr) { + alert('오류: ' + xhr.responseJSON.error); + } + }); + }); + + // 입고장 업로드 + $('#purchaseUploadForm').on('submit', function(e) { + e.preventDefault(); + + const supplierId = $('#uploadSupplier').val(); + if (!supplierId) { + alert('도매상을 선택해주세요.'); + return; + } + + const formData = new FormData(); + const fileInput = $('#purchaseFile')[0]; + + if (fileInput.files.length === 0) { + alert('파일을 선택해주세요.'); + return; + } + + formData.append('file', fileInput.files[0]); + formData.append('supplier_id', supplierId); + + $('#uploadResult').html('
업로드 중...
'); + + $.ajax({ + url: '/api/upload/purchase', + method: 'POST', + data: formData, + processData: false, + contentType: false, + success: function(response) { + if (response.success) { + let summaryHtml = ''; + if (response.summary) { + summaryHtml = `
+ + 형식: ${response.summary.format}
+ 처리: ${response.summary.processed_rows}개 라인
+ 품목: ${response.summary.total_items}종
+ 수량: ${response.summary.total_quantity}
+ 금액: ${response.summary.total_amount} +
`; + } + + $('#uploadResult').html( + `
+ ${response.message} + ${summaryHtml} +
` + ); + $('#purchaseUploadForm')[0].reset(); + + // 입고장 목록 새로고침 + loadPurchaseReceipts(); + } + }, + error: function(xhr) { + $('#uploadResult').html( + `
+ 오류: ${xhr.responseJSON.error} +
` + ); + } + }); + }); + + // 검색 기능 + $('#patientSearch').on('keyup', function() { + const value = $(this).val().toLowerCase(); + $('#patientsList tr').filter(function() { + $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1); + }); + }); + + $('#inventorySearch').on('keyup', function() { + const value = $(this).val().toLowerCase(); + $('#inventoryList tr').filter(function() { + $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1); + }); + }); + + // 헬퍼 함수들 + function loadPatientsForSelect() { + $.get('/api/patients', function(response) { + if (response.success) { + const select = $('#compoundPatient'); + select.empty().append(''); + + response.data.forEach(patient => { + select.append(``); + }); + } + }); + } + + function loadFormulasForSelect() { + $.get('/api/formulas', function(response) { + if (response.success) { + const select = $('#compoundFormula'); + select.empty().append(''); + + // 직접조제 옵션 추가 + select.append(''); + + // 등록된 처방 추가 + if (response.data.length > 0) { + select.append(''); + response.data.forEach(formula => { + select.append(``); + }); + select.append(''); + } + } + }); + } + + function loadHerbsForSelect(selectElement) { + $.get('/api/herbs/masters', function(response) { + if (response.success) { + selectElement.empty().append(''); + + // 재고가 있는 약재만 필터링하여 표시 + const herbsWithStock = response.data.filter(herb => herb.has_stock === 1); + + herbsWithStock.forEach(herb => { + // ingredient_code를 value로 사용하고, 한글명(한자명) 형식으로 표시 + let displayName = herb.herb_name; + if (herb.herb_name_hanja) { + displayName += ` (${herb.herb_name_hanja})`; + } + selectElement.append(``); + }); + } + }).fail(function(error) { + console.error('Failed to load herbs:', error); + }); + } + + // ingredient_code 기반으로 제품 옵션 로드 + function loadProductOptions(row, ingredientCode, herbName) { + $.get(`/api/herbs/by-ingredient/${ingredientCode}`, function(response) { + if (response.success) { + const productSelect = row.find('.product-select'); + productSelect.empty(); + + if (response.data.length === 0) { + productSelect.append(''); + productSelect.prop('disabled', true); + } else { + productSelect.append(''); + response.data.forEach(product => { + const stockInfo = product.stock_quantity > 0 ? `(재고: ${product.stock_quantity.toFixed(1)}g)` : '(재고 없음)'; + const companyInfo = product.company_name ? `[${product.company_name}]` : ''; + productSelect.append(``); + }); + productSelect.prop('disabled', false); + } + } + }).fail(function() { + console.error(`Failed to load products for ingredient code: ${ingredientCode}`); + }); + } + + // 원산지별 재고 옵션 로드 + function loadOriginOptions(herbId, requiredQty) { + $.get(`/api/herbs/${herbId}/available-lots`, function(response) { + if (response.success) { + const selectElement = $(`tr[data-herb-id="${herbId}"] .origin-select`); + selectElement.empty(); + + const origins = response.data.origins; + + if (origins.length === 0) { + selectElement.append(''); + selectElement.prop('disabled', true); + $(`tr[data-herb-id="${herbId}"] .stock-status`) + .html('재고 없음'); + } else { + selectElement.append(''); + + // 로트가 2개 이상인 경우 수동 배분 옵션 추가 + const totalLots = origins.reduce((sum, o) => sum + o.lot_count, 0); + if (totalLots > 1) { + selectElement.append(''); + } + + origins.forEach(origin => { + const stockStatus = origin.total_quantity >= requiredQty ? '' : ' (재고 부족)'; + const priceInfo = `${formatCurrency(origin.min_price)}/g`; + + // 해당 원산지의 display_name 목록 생성 + let displayNames = []; + if (origin.lots && origin.lots.length > 0) { + origin.lots.forEach(lot => { + if (lot.display_name) { + displayNames.push(lot.display_name); + } + }); + } + + // 고유한 display_name만 표시 (중복 제거) + const uniqueDisplayNames = [...new Set(displayNames)]; + const displayNameText = uniqueDisplayNames.length > 0 + ? ` [${uniqueDisplayNames.join(', ')}]` + : ''; + + const option = ``; + selectElement.append(option); + }); + + selectElement.prop('disabled', false); + + // 원산지 선택 변경 이벤트 (수동 배분 모달 트리거) + selectElement.off('change').on('change', function() { + const selectedValue = $(this).val(); + const row = $(this).closest('tr'); + + if (selectedValue === 'manual') { + // 현재 행의 실제 필요량 재계산 + const gramsPerCheop = parseFloat(row.find('.grams-per-cheop').val()) || 0; + const cheopTotal = parseFloat($('#cheopTotal').val()) || 0; + const actualRequiredQty = gramsPerCheop * cheopTotal; + + // 수동 배분 모달 열기 (재계산된 필요량 사용) + openLotAllocationModal(herbId, actualRequiredQty, row, response.data); + } else { + // 기존 자동/원산지 선택 - lot_assignments 제거 + row.removeAttr('data-lot-assignments'); + } + }); + + // 재고 상태 업데이트 + const totalAvailable = response.data.total_quantity; + const statusElement = $(`tr[data-herb-id="${herbId}"] .stock-status`); + + if (totalAvailable >= requiredQty) { + statusElement.html(`충분 (${totalAvailable.toFixed(1)}g)`); + } else { + statusElement.html(`부족 (${totalAvailable.toFixed(1)}g)`); + } + } + } + }); + } + + // 재고 원장 보기 + let currentLedgerData = []; // 원본 데이터 저장 + + function viewStockLedger(herbId, herbName) { + const url = herbId ? `/api/stock-ledger?herb_id=${herbId}` : '/api/stock-ledger'; + + $.get(url, function(response) { + if (response.success) { + // 원본 데이터 저장 + currentLedgerData = response.ledger; + + // 헤더 업데이트 + if (herbName) { + $('#stockLedgerModal .modal-title').html(` ${herbName} 입출고 원장`); + } else { + $('#stockLedgerModal .modal-title').html(` 전체 입출고 원장`); + } + + // 필터 적용하여 표시 + applyLedgerFilters(); + + // 약재 필터 옵션 업데이트 + const herbFilter = $('#ledgerHerbFilter'); + if (herbFilter.find('option').length <= 1) { + response.summary.forEach(herb => { + herbFilter.append(``); + }); + } + + $('#stockLedgerModal').modal('show'); + } + }).fail(function() { + alert('입출고 내역을 불러오는데 실패했습니다.'); + }); + } + + // 필터 적용 함수 + function applyLedgerFilters() { + const typeFilter = $('#ledgerTypeFilter').val(); + const tbody = $('#stockLedgerList'); + tbody.empty(); + + // 필터링된 데이터 + let filteredData = currentLedgerData; + + // 타입 필터 적용 + if (typeFilter) { + filteredData = currentLedgerData.filter(entry => entry.event_type === typeFilter); + } + + // 데이터 표시 + filteredData.forEach(entry => { + let typeLabel = ''; + let typeBadge = ''; + switch(entry.event_type) { + case 'PURCHASE': + case 'RECEIPT': + typeLabel = '입고'; + typeBadge = 'badge bg-success'; + break; + case 'CONSUME': + typeLabel = '출고'; + typeBadge = 'badge bg-danger'; + break; + case 'ADJUST': + typeLabel = '보정'; + typeBadge = 'badge bg-warning'; + break; + default: + typeLabel = entry.event_type; + typeBadge = 'badge bg-secondary'; + } + + const quantity = Math.abs(entry.quantity_delta); + const sign = entry.quantity_delta > 0 ? '+' : '-'; + const quantityDisplay = entry.quantity_delta > 0 + ? `+${quantity.toFixed(1)}g` + : `-${quantity.toFixed(1)}g`; + + const referenceInfo = entry.patient_name + ? `${entry.patient_name}` + : entry.supplier_name || '-'; + + tbody.append(` + + ${entry.event_time} + ${typeLabel} + ${entry.herb_name} + ${quantityDisplay} + ${entry.unit_cost_per_g ? formatCurrency(entry.unit_cost_per_g) + '/g' : '-'} + ${entry.origin_country || '-'} + ${referenceInfo} + ${entry.reference_no || '-'} + + `); + }); + + // 데이터가 없는 경우 + if (filteredData.length === 0) { + tbody.append(` + + 데이터가 없습니다. + + `); + } + } + + // 입출고 원장 모달 버튼 이벤트 + $('#showStockLedgerBtn').on('click', function() { + viewStockLedger(null, null); + }); + + // 필터 변경 이벤트 + $('#ledgerHerbFilter').on('change', function() { + const herbId = $(this).val(); + + // 약재 필터 변경 시 데이터 재로드 + if (herbId) { + const herbName = $('#ledgerHerbFilter option:selected').text(); + viewStockLedger(herbId, herbName); + } else { + viewStockLedger(null, null); + } + }); + + // 타입 필터 변경 이벤트 (현재 데이터에서 필터링만) + $('#ledgerTypeFilter').on('change', function() { + applyLedgerFilters(); + }); + + // ==================== 재고 보정 ==================== + + // 재고 보정 모달 열기 + $('#showStockAdjustmentBtn').on('click', function() { + // 현재 날짜 설정 + $('#adjustmentDate').val(new Date().toISOString().split('T')[0]); + $('#adjustmentItemsList').empty(); + $('#stockAdjustmentForm')[0].reset(); + $('#stockAdjustmentModal').modal('show'); + }); + + // 재고 보정 내역 모달 열기 + $('#showAdjustmentHistoryBtn').on('click', function() { + loadAdjustmentHistory(); + }); + + // 재고 보정 내역 로드 + function loadAdjustmentHistory() { + $.get('/api/stock-adjustments', function(response) { + if (response.success) { + const tbody = $('#adjustmentHistoryList'); + tbody.empty(); + + if (response.data.length === 0) { + tbody.append(` + + 보정 내역이 없습니다. + + `); + } else { + response.data.forEach(adj => { + // 보정 유형 한글 변환 + let typeLabel = ''; + switch(adj.adjustment_type) { + case 'LOSS': typeLabel = '감모/손실'; break; + case 'FOUND': typeLabel = '발견'; break; + case 'RECOUNT': typeLabel = '재고조사'; break; + case 'DAMAGE': typeLabel = '파손'; break; + case 'EXPIRE': typeLabel = '유통기한 경과'; break; + default: typeLabel = adj.adjustment_type; + } + + tbody.append(` + + ${adj.adjustment_date} + ${adj.adjustment_no} + ${typeLabel} + ${adj.detail_count || 0}개 + ${adj.created_by || '-'} + ${adj.notes || '-'} + + + + + `); + }); + + // 상세보기 버튼 이벤트 + $('.view-adjustment-detail').on('click', function() { + const adjustmentId = $(this).data('id'); + viewAdjustmentDetail(adjustmentId); + }); + } + + $('#adjustmentHistoryModal').modal('show'); + } + }).fail(function() { + alert('보정 내역을 불러오는데 실패했습니다.'); + }); + } + + // 재고 보정 상세 조회 + function viewAdjustmentDetail(adjustmentId) { + $.get(`/api/stock-adjustments/${adjustmentId}`, function(response) { + if (response.success) { + const data = response.data; + + // 보정 정보 표시 + $('#detailAdjustmentNo').text(data.adjustment_no); + $('#detailAdjustmentDate').text(data.adjustment_date); + + // 보정 유형 한글 변환 + let typeLabel = ''; + switch(data.adjustment_type) { + case 'LOSS': typeLabel = '감모/손실'; break; + case 'FOUND': typeLabel = '발견'; break; + case 'RECOUNT': typeLabel = '재고조사'; break; + case 'DAMAGE': typeLabel = '파손'; break; + case 'EXPIRE': typeLabel = '유통기한 경과'; break; + default: typeLabel = data.adjustment_type; + } + $('#detailAdjustmentType').html(`${typeLabel}`); + $('#detailAdjustmentCreatedBy').text(data.created_by || '-'); + $('#detailAdjustmentNotes').text(data.notes || '-'); + + // 보정 상세 항목 표시 + const itemsBody = $('#detailAdjustmentItems'); + itemsBody.empty(); + + if (data.details && data.details.length > 0) { + data.details.forEach(item => { + const delta = item.quantity_delta; + let deltaHtml = ''; + if (delta > 0) { + deltaHtml = `+${delta.toFixed(1)}g`; + } else if (delta < 0) { + deltaHtml = `${delta.toFixed(1)}g`; + } else { + deltaHtml = '0g'; + } + + itemsBody.append(` + + ${item.herb_name} + ${item.insurance_code || '-'} + ${item.origin_country || '-'} + #${item.lot_id} + ${item.quantity_before.toFixed(1)}g + ${item.quantity_after.toFixed(1)}g + ${deltaHtml} + ${item.reason || '-'} + + `); + }); + } + + // 보정 상세 모달 표시 + $('#adjustmentDetailModal').modal('show'); + } + }).fail(function() { + alert('보정 상세 정보를 불러오는데 실패했습니다.'); + }); + } + + // 보정 대상 약재 추가 + let adjustmentItemCount = 0; + $('#addAdjustmentItemBtn').on('click', function() { + addAdjustmentItemRow(); + }); + + function addAdjustmentItemRow() { + adjustmentItemCount++; + const rowId = `adj-item-${adjustmentItemCount}`; + + const newRow = $(` + + + + + + + + - + + + + - + + + + + + + + `); + + $('#adjustmentItemsList').append(newRow); + + // 약재 목록 로드 + loadHerbsForSelect(newRow.find('.adj-herb-select')); + + // 약재 선택 이벤트 + newRow.find('.adj-herb-select').on('change', function() { + const herbId = $(this).val(); + const row = $(this).closest('tr'); + + if (herbId) { + loadLotsForAdjustment(herbId, row); + } else { + row.find('.adj-lot-select').empty().append('').prop('disabled', true); + row.find('.before-qty').text('-'); + row.find('.after-qty-input').val(''); + row.find('.delta-qty').text('-'); + } + }); + + // 로트 선택 이벤트 + newRow.find('.adj-lot-select').on('change', function() { + const selectedOption = $(this).find('option:selected'); + const row = $(this).closest('tr'); + + if (selectedOption.val()) { + const beforeQty = parseFloat(selectedOption.data('qty')) || 0; + row.find('.before-qty').text(beforeQty.toFixed(1) + 'g'); + row.data('before-qty', beforeQty); + + // 기존 변경후 값이 있으면 델타 재계산 + const afterQty = parseFloat(row.find('.after-qty-input').val()); + if (!isNaN(afterQty)) { + updateDelta(row, beforeQty, afterQty); + } + } else { + row.find('.before-qty').text('-'); + row.find('.after-qty-input').val(''); + row.find('.delta-qty').text('-'); + } + }); + + // 변경후 수량 입력 이벤트 + newRow.find('.after-qty-input').on('input', function() { + const row = $(this).closest('tr'); + const beforeQty = row.data('before-qty') || 0; + const afterQty = parseFloat($(this).val()) || 0; + + updateDelta(row, beforeQty, afterQty); + }); + + // 삭제 버튼 + newRow.find('.remove-adj-item').on('click', function() { + $(this).closest('tr').remove(); + }); + } + + // 약재별 로트 목록 로드 + function loadLotsForAdjustment(herbId, row) { + $.get(`/api/inventory/detail/${herbId}`, function(response) { + if (response.success) { + const lotSelect = row.find('.adj-lot-select'); + lotSelect.empty(); + lotSelect.append(''); + + const data = response.data; + + // 원산지별로 로트 표시 + data.origins.forEach(origin => { + const optgroup = $(``); + + origin.lots.forEach(lot => { + optgroup.append(` + + `); + }); + + lotSelect.append(optgroup); + }); + + lotSelect.prop('disabled', false); + } + }).fail(function() { + alert('재고 정보를 불러오는데 실패했습니다.'); + }); + } + + // 델타 계산 및 표시 + function updateDelta(row, beforeQty, afterQty) { + const delta = afterQty - beforeQty; + const deltaElement = row.find('.delta-qty'); + + if (delta > 0) { + deltaElement.html(`+${delta.toFixed(1)}g`); + } else if (delta < 0) { + deltaElement.html(`${delta.toFixed(1)}g`); + } else { + deltaElement.html('0g'); + } + + row.data('delta', delta); + } + + // 재고 보정 저장 버튼 + $('#saveAdjustmentBtn').on('click', function() { + saveStockAdjustment(); + }); + + // 재고 보정 저장 + $('#stockAdjustmentForm').on('submit', function(e) { + e.preventDefault(); + saveStockAdjustment(); + }); + + function saveStockAdjustment() { + const items = []; + let hasError = false; + + $('#adjustmentItemsList tr').each(function() { + const herbId = $(this).find('.adj-herb-select').val(); + const lotId = $(this).find('.adj-lot-select').val(); + const beforeQty = $(this).data('before-qty'); + const afterQty = parseFloat($(this).find('.after-qty-input').val()); + const delta = $(this).data('delta'); + const reason = $(this).find('.reason-input').val(); + + if (!herbId || !lotId) { + hasError = true; + return false; + } + + items.push({ + herb_item_id: parseInt(herbId), + lot_id: parseInt(lotId), + quantity_before: beforeQty, + quantity_after: afterQty, + quantity_delta: delta, + reason: reason + }); + }); + + if (hasError) { + alert('모든 항목의 약재와 로트를 선택해주세요.'); + return; + } + + if (items.length === 0) { + alert('보정할 항목을 추가해주세요.'); + return; + } + + const adjustmentData = { + adjustment_date: $('#adjustmentDate').val(), + adjustment_type: $('#adjustmentType').val(), + created_by: $('#adjustmentCreatedBy').val() || 'SYSTEM', + notes: $('#adjustmentNotes').val(), + details: items // API expects 'details', not 'items' + }; + + $.ajax({ + url: '/api/stock-adjustments', + method: 'POST', + contentType: 'application/json', + data: JSON.stringify(adjustmentData), + success: function(response) { + if (response.success) { + alert(`재고 보정이 완료되었습니다.\n보정번호: ${response.adjustment_no}\n항목 수: ${items.length}개`); + $('#stockAdjustmentModal').modal('hide'); + + // 재고 목록 새로고침 + loadInventory(); + } + }, + error: function(xhr) { + alert('오류: ' + (xhr.responseJSON?.error || '재고 보정 실패')); + } + }); + } + + function formatCurrency(amount) { + if (amount === null || amount === undefined) return '0원'; + return new Intl.NumberFormat('ko-KR', { + style: 'currency', + currency: 'KRW' + }).format(amount); + } + + // === 재고 자산 계산 설정 기능 === + + // 재고 현황 로드 (모드 포함) + function loadInventorySummary() { + const mode = localStorage.getItem('inventoryMode') || 'all'; + + $.get(`/api/inventory/summary?mode=${mode}`, function(response) { + if (response.success) { + $('#totalHerbs').text(response.data.length); + $('#inventoryValue').text(formatCurrency(response.summary.total_value)); + + // 모드 표시 업데이트 + if (response.summary.calculation_mode) { + $('#inventoryMode').text(response.summary.calculation_mode.mode_label); + + // 설정 모달이 열려있으면 정보 표시 + if ($('#inventorySettingsModal').hasClass('show')) { + updateModeInfo(response.summary.calculation_mode); + } + } + } + }); + } + + // 재고 계산 설정 저장 + window.saveInventorySettings = function() { + const selectedMode = $('input[name="inventoryMode"]:checked').val(); + + // localStorage에 저장 + localStorage.setItem('inventoryMode', selectedMode); + inventoryCalculationMode = selectedMode; + + // 재고 현황 다시 로드 + loadInventorySummary(); + + // 모달 닫기 + $('#inventorySettingsModal').modal('hide'); + + // 성공 메시지 + showToast('success', '재고 계산 설정이 변경되었습니다.'); + } + + // 모드 정보 업데이트 + function updateModeInfo(modeInfo) { + let infoHtml = ''; + + if (modeInfo.mode === 'all' && modeInfo.no_receipt_lots !== undefined) { + if (modeInfo.no_receipt_lots > 0) { + infoHtml = ` +

• 입고장 없는 LOT: ${modeInfo.no_receipt_lots}개

+

• 해당 재고 가치: ${formatCurrency(modeInfo.no_receipt_value)}

+ `; + } else { + infoHtml = '

• 모든 LOT이 입고장과 연결되어 있습니다.

'; + } + } else if (modeInfo.mode === 'receipt_only') { + infoHtml = '

• 입고장과 연결된 LOT만 계산합니다.

'; + } else if (modeInfo.mode === 'verified') { + infoHtml = '

• 검증 확인된 LOT만 계산합니다.

'; + } + + if (infoHtml) { + $('#modeInfoContent').html(infoHtml); + $('#modeInfo').show(); + } else { + $('#modeInfo').hide(); + } + } + + // 설정 모달이 열릴 때 현재 모드 설정 + $('#inventorySettingsModal').on('show.bs.modal', function() { + const currentMode = localStorage.getItem('inventoryMode') || 'all'; + $(`input[name="inventoryMode"][value="${currentMode}"]`).prop('checked', true); + + // 현재 모드 정보 로드 + $.get(`/api/inventory/summary?mode=${currentMode}`, function(response) { + if (response.success && response.summary.calculation_mode) { + updateModeInfo(response.summary.calculation_mode); + } + }); + }); + + // 모드 선택 시 즉시 정보 업데이트 + $('input[name="inventoryMode"]').on('change', function() { + const selectedMode = $(this).val(); + + // 선택한 모드의 정보를 미리보기로 로드 + $.get(`/api/inventory/summary?mode=${selectedMode}`, function(response) { + if (response.success && response.summary.calculation_mode) { + updateModeInfo(response.summary.calculation_mode); + } + }); + }); + + // Toast 메시지 표시 함수 (없으면 추가) + function showToast(type, message) { + const toastHtml = ` + + `; + + // Toast 컨테이너가 없으면 생성 + if (!$('#toastContainer').length) { + $('body').append('
'); + } + + const $toast = $(toastHtml); + $('#toastContainer').append($toast); + + const toast = new bootstrap.Toast($toast[0]); + toast.show(); + + // 5초 후 자동 제거 + setTimeout(() => { + $toast.remove(); + }, 5000); + } + + // ==================== 주성분코드 기반 약재 관리 ==================== + let allHerbMasters = []; // 전체 약재 데이터 저장 + let currentFilter = 'all'; // 현재 필터 상태 + + // 약재 마스터 목록 로드 + function loadHerbMasters() { + $.get('/api/herbs/masters', function(response) { + if (response.success) { + allHerbMasters = response.data; + + // 통계 정보 표시 + const summary = response.summary; + $('#herbMasterSummary').html(` +
+
+
📊 급여 약재 현황
+
+
+ 전체: ${summary.total_herbs}개 주성분 +
+
+ 재고 있음: ${summary.herbs_with_stock}개 +
+
+ 재고 없음: ${summary.herbs_without_stock}개 +
+
+ 보유율: ${summary.coverage_rate}% +
+
+
+
+
+
+ ${summary.herbs_with_stock} / ${summary.total_herbs} +
+
+
+
+ `); + + // 목록 표시 + displayHerbMasters(allHerbMasters); + } + }); + } + + // 약재 목록 표시 + function displayHerbMasters(herbs) { + const tbody = $('#herbMastersList'); + tbody.empty(); + + // 필터링 + let filteredHerbs = herbs; + if (currentFilter === 'stock') { + filteredHerbs = herbs.filter(h => h.has_stock); + } else if (currentFilter === 'no-stock') { + filteredHerbs = herbs.filter(h => !h.has_stock); + } + + // 검색 필터 + const searchText = $('#herbSearch').val().toLowerCase(); + if (searchText) { + filteredHerbs = filteredHerbs.filter(h => + h.herb_name.toLowerCase().includes(searchText) || + h.ingredient_code.toLowerCase().includes(searchText) + ); + } + + // 효능 필터 + const efficacyFilter = $('#efficacyFilter').val(); + if (efficacyFilter) { + filteredHerbs = filteredHerbs.filter(h => + h.efficacy_tags && h.efficacy_tags.includes(efficacyFilter) + ); + } + + // 표시 + filteredHerbs.forEach(herb => { + // 효능 태그 표시 + let efficacyTags = ''; + if (herb.efficacy_tags && herb.efficacy_tags.length > 0) { + efficacyTags = herb.efficacy_tags.map(tag => + `${tag}` + ).join(''); + } + + // 상태 표시 + const statusBadge = herb.has_stock + ? '재고 있음' + : '재고 없음'; + + // 재고량 표시 + const stockDisplay = herb.stock_quantity > 0 + ? `${herb.stock_quantity.toFixed(1)}g` + : '-'; + + // 평균단가 표시 + const priceDisplay = herb.avg_price > 0 + ? formatCurrency(herb.avg_price) + : '-'; + + tbody.append(` + + ${herb.ingredient_code} + ${herb.herb_name} + ${efficacyTags} + ${stockDisplay} + ${priceDisplay} + ${herb.product_count || 0}개 + ${statusBadge} + + + + + `); + }); + + if (filteredHerbs.length === 0) { + tbody.append('표시할 약재가 없습니다.'); + } + } + + // 약재 상세 보기 + function viewHerbDetail(ingredientCode) { + // TODO: 약재 상세 모달 구현 + console.log('View detail for:', ingredientCode); + } + + // 필터 버튼 이벤트 + $('#herbs .btn-group button[data-filter]').on('click', function() { + $('#herbs .btn-group button').removeClass('active'); + $(this).addClass('active'); + currentFilter = $(this).data('filter'); + displayHerbMasters(allHerbMasters); + }); + + // 검색 이벤트 + $('#herbSearch').on('keyup', function() { + displayHerbMasters(allHerbMasters); + }); + + // 효능 필터 이벤트 + $('#efficacyFilter').on('change', function() { + displayHerbMasters(allHerbMasters); + }); + + // 약재 관리 페이지가 활성화되면 데이터 로드 + $('.nav-link[data-page="herbs"]').on('click', function() { + setTimeout(() => loadHerbMasters(), 100); + }); + + // ==================== 로트 배분 모달 관련 함수들 ==================== + + // 로트 배분 모달 열기 + window.openLotAllocationModal = function(herbId, requiredQty, row, data) { + // 디버깅: 전달받은 필요량 확인 + console.log('로트 배분 모달 열기:', { + herbId: herbId, + requiredQty: requiredQty, + herbName: data.herb_name, + gramsPerCheop: row.find('.grams-per-cheop').val(), + cheopTotal: $('#cheopTotal').val() + }); + + currentLotAllocation = { + herbId: herbId, + requiredQty: requiredQty, + row: row, + data: data + }; + + // 모달 초기화 + $('#lotAllocationHerbName').text(data.herb_name); + $('#lotAllocationRequired').text(requiredQty.toFixed(1)); + $('#lotAllocationError').addClass('d-none'); + + // 로트 목록 생성 + const tbody = $('#lotAllocationList'); + tbody.empty(); + + // 모든 로트를 하나의 목록으로 표시 + let allLots = []; + data.origins.forEach(origin => { + origin.lots.forEach(lot => { + allLots.push({ + ...lot, + origin: origin.origin_country + }); + }); + }); + + // 단가 순으로 정렬 + allLots.sort((a, b) => a.unit_price_per_g - b.unit_price_per_g); + + allLots.forEach(lot => { + tbody.append(` + + #${lot.lot_id} + ${lot.origin || '미지정'} + ${lot.quantity_onhand.toFixed(1)}g + ${formatCurrency(lot.unit_price_per_g)}/g + + + + 0원 + + `); + }); + + // 입력 이벤트 + $('.lot-allocation-input').on('input', function() { + updateLotAllocationSummary(); + }); + + $('#lotAllocationModal').modal('show'); + }; + + // 로트 배분 합계 업데이트 + function updateLotAllocationSummary() { + let totalQty = 0; + let totalCost = 0; + + $('.lot-allocation-input').each(function() { + const qty = parseFloat($(this).val()) || 0; + const price = parseFloat($(this).data('price')) || 0; + const subtotal = qty * price; + + totalQty += qty; + totalCost += subtotal; + + // 소계 표시 + $(this).closest('tr').find('.lot-subtotal').text(formatCurrency(subtotal) + '원'); + }); + + $('#lotAllocationTotal').text(totalQty.toFixed(1)); + $('#lotAllocationSumQty').text(totalQty.toFixed(1) + 'g'); + $('#lotAllocationSumCost').text(formatCurrency(totalCost) + '원'); + + // 검증 + const required = currentLotAllocation.requiredQty; + const diff = Math.abs(totalQty - required); + + if (diff > 0.01) { + $('#lotAllocationError') + .removeClass('d-none') + .text(`필요량(${required.toFixed(1)}g)과 배분 합계(${totalQty.toFixed(1)}g)가 일치하지 않습니다.`); + $('#lotAllocationConfirmBtn').prop('disabled', true); + } else { + $('#lotAllocationError').addClass('d-none'); + $('#lotAllocationConfirmBtn').prop('disabled', false); + } + } + + // 자동 배분 + $('#lotAllocationAutoBtn').on('click', function() { + let remaining = currentLotAllocation.requiredQty; + + $('.lot-allocation-input').each(function() { + const maxAvailable = parseFloat($(this).data('max')); + const allocate = Math.min(remaining, maxAvailable); + + $(this).val(allocate.toFixed(1)); + remaining -= allocate; + + if (remaining <= 0) return false; // break + }); + + updateLotAllocationSummary(); + }); + + // 로트 배분 확인 + $('#lotAllocationConfirmBtn').on('click', function() { + const allocations = []; + + $('.lot-allocation-input').each(function() { + const qty = parseFloat($(this).val()) || 0; + if (qty > 0) { + const lotId = $(this).closest('tr').data('lot-id'); + allocations.push({ + lot_id: lotId, + quantity: qty + }); + } + }); + + // 현재 행에 로트 배분 정보 저장 + currentLotAllocation.row.attr('data-lot-assignments', JSON.stringify(allocations)); + + // 상태 표시 업데이트 + const statusElement = currentLotAllocation.row.find('.stock-status'); + statusElement.html(`수동 배분 (${allocations.length}개 로트)`); + + $('#lotAllocationModal').modal('hide'); + }); + + // 조제 실행 시 lot_assignments 포함 + window.getIngredientDataForCompound = function() { + const ingredients = []; + + $('#compoundIngredients tr').each(function() { + const herbId = $(this).attr('data-herb-id'); + if (herbId) { + const ingredient = { + herb_item_id: parseInt(herbId), + grams_per_cheop: parseFloat($(this).find('.grams-per-cheop').val()) || 0, + total_grams: parseFloat($(this).find('.total-grams').text()) || 0, + origin: $(this).find('.origin-select').val() || 'auto' + }; + + // 수동 로트 배분이 있는 경우 + const lotAssignments = $(this).attr('data-lot-assignments'); + if (lotAssignments) { + ingredient.lot_assignments = JSON.parse(lotAssignments); + ingredient.origin = 'manual'; // origin을 manual로 설정 + } + + ingredients.push(ingredient); + } + }); + + return ingredients; + }; + + // ==================== 약재 정보 시스템 ==================== + + // 약재 정보 페이지 로드 + window.loadHerbInfo = function loadHerbInfo() { + loadAllHerbsInfo(); + loadEfficacyTags(); + + // 뷰 전환 버튼 + $('#herb-info button[data-view]').on('click', function() { + $('#herb-info button[data-view]').removeClass('active'); + $(this).addClass('active'); + + const view = $(this).data('view'); + if (view === 'search') { + $('#herb-search-section').show(); + $('#herb-efficacy-section').hide(); + loadAllHerbsInfo(); + } else if (view === 'efficacy') { + $('#herb-search-section').hide(); + $('#herb-efficacy-section').show(); + loadEfficacyTagButtons(); + } else if (view === 'category') { + $('#herb-search-section').show(); + $('#herb-efficacy-section').hide(); + loadHerbsByCategory(); + } + }); + + // 검색 버튼 + $('#herbSearchBtn').off('click').on('click', function() { + const searchTerm = $('#herbSearchInput').val(); + searchHerbs(searchTerm); + }); + + // 엔터 키로 검색 + $('#herbSearchInput').off('keypress').on('keypress', function(e) { + if (e.which === 13) { + searchHerbs($(this).val()); + } + }); + + // 필터 변경 + $('#herbInfoEfficacyFilter, #herbInfoPropertyFilter').off('change').on('change', function() { + filterHerbs(); + }); + } + + // 모든 약재 정보 로드 + window.loadAllHerbsInfo = function loadAllHerbsInfo() { + $.get('/api/herbs/masters', function(response) { + if (response.success) { + displayHerbCards(response.data); + } + }); + } + + // 약재 카드 표시 + window.displayHerbCards = function displayHerbCards(herbs) { + const grid = $('#herbInfoGrid'); + grid.empty(); + + if (herbs.length === 0) { + grid.html('
검색 결과가 없습니다.
'); + return; + } + + herbs.forEach(herb => { + // 재고 상태에 따른 배지 색상 + const stockBadge = herb.has_stock ? + '재고있음' : + '재고없음'; + + // 효능 태그 HTML + let tagsHtml = ''; + if (herb.efficacy_tags && herb.efficacy_tags.length > 0) { + tagsHtml = herb.efficacy_tags.slice(0, 3).map(tag => + `${tag}` + ).join(''); + if (herb.efficacy_tags.length > 3) { + tagsHtml += `+${herb.efficacy_tags.length - 3}`; + } + } + + const card = ` +
+
+
+
+
+ ${herb.herb_name} + ${herb.herb_name_hanja ? `(${herb.herb_name_hanja})` : ''} +
+ ${stockBadge} +
+

+ ${herb.ingredient_code} +

+
+ ${tagsHtml || '태그 없음'} +
+ ${herb.main_effects ? + `

${herb.main_effects.substring(0, 50)}...

` : + '

효능 정보 없음

' + } +
+
+
+ `; + grid.append(card); + }); + + // 카드 클릭 이벤트 + $('.herb-info-card').off('click').on('click', function() { + const ingredientCode = $(this).data('ingredient-code'); + showHerbDetail(ingredientCode); + }); + } + + // 약재 상세 정보 표시 + function showHerbDetail(ingredientCode) { + // herb_master_extended에서 herb_id 찾기 + $.get('/api/herbs/masters', function(response) { + if (response.success) { + const herb = response.data.find(h => h.ingredient_code === ingredientCode); + if (herb && herb.herb_id) { + // 확장 정보 조회 + $.get(`/api/herbs/${herb.herb_id}/extended`, function(detailResponse) { + displayHerbDetailModal(detailResponse); + }).fail(function() { + // 확장 정보가 없으면 기본 정보만 표시 + displayHerbDetailModal(herb); + }); + } + } + }); + } + + // 상세 정보 모달 표시 + function displayHerbDetailModal(herb) { + $('#herbDetailName').text(herb.name_korean || herb.herb_name || '-'); + $('#herbDetailHanja').text(herb.name_hanja || herb.herb_name_hanja || ''); + + // 기본 정보 + $('#detailIngredientCode').text(herb.ingredient_code || '-'); + $('#detailLatinName').text(herb.name_latin || herb.herb_name_latin || '-'); + $('#detailMedicinalPart').text(herb.medicinal_part || '-'); + $('#detailOriginPlant').text(herb.origin_plant || '-'); + + // 성미귀경 + $('#detailProperty').text(herb.property || '-'); + $('#detailTaste').text(herb.taste || '-'); + $('#detailMeridian').text(herb.meridian_tropism || '-'); + + // 효능효과 + $('#detailMainEffects').text(herb.main_effects || '-'); + $('#detailIndications').text(herb.indications || '-'); + + // 효능 태그 + if (herb.efficacy_tags && herb.efficacy_tags.length > 0) { + const tagsHtml = herb.efficacy_tags.map(tag => { + const strength = tag.strength || 3; + const sizeClass = strength >= 4 ? 'fs-5' : 'fs-6'; + return `${tag.name || tag}`; + }).join(''); + $('#detailEfficacyTags').html(tagsHtml); + } else { + $('#detailEfficacyTags').html('태그 없음'); + } + + // 용법용량 + $('#detailDosageRange').text(herb.dosage_range || '-'); + $('#detailDosageMax').text(herb.dosage_max || '-'); + $('#detailPreparation').text(herb.preparation_method || '-'); + + // 안전성 + $('#detailContraindications').text(herb.contraindications || '-'); + $('#detailPrecautions').text(herb.precautions || '-'); + + // 성분정보 + $('#detailActiveCompounds').text(herb.active_compounds || '-'); + + // 임상응용 + $('#detailPharmacological').text(herb.pharmacological_effects || '-'); + $('#detailClinical').text(herb.clinical_applications || '-'); + + // 정보 수정 버튼 + $('#editHerbInfoBtn').off('click').on('click', function() { + editHerbInfo(herb.herb_id || herb.ingredient_code); + }); + + $('#herbDetailModal').modal('show'); + } + + // 약재 검색 + function searchHerbs(searchTerm) { + if (!searchTerm) { + loadAllHerbsInfo(); + return; + } + + $.get('/api/herbs/masters', function(response) { + if (response.success) { + const filtered = response.data.filter(herb => { + const term = searchTerm.toLowerCase(); + return (herb.herb_name && herb.herb_name.toLowerCase().includes(term)) || + (herb.herb_name_hanja && herb.herb_name_hanja.includes(term)) || + (herb.ingredient_code && herb.ingredient_code.toLowerCase().includes(term)) || + (herb.main_effects && herb.main_effects.toLowerCase().includes(term)) || + (herb.efficacy_tags && herb.efficacy_tags.some(tag => tag.toLowerCase().includes(term))); + }); + displayHerbCards(filtered); + } + }); + } + + // 필터 적용 + function filterHerbs() { + const efficacyFilter = $('#herbInfoEfficacyFilter').val(); + const propertyFilter = $('#herbInfoPropertyFilter').val(); + + $.get('/api/herbs/masters', function(response) { + if (response.success) { + let filtered = response.data; + + if (efficacyFilter) { + filtered = filtered.filter(herb => + herb.efficacy_tags && herb.efficacy_tags.includes(efficacyFilter) + ); + } + + if (propertyFilter) { + filtered = filtered.filter(herb => + herb.property === propertyFilter + ); + } + + displayHerbCards(filtered); + } + }); + } + + // 효능 태그 로드 + function loadEfficacyTags() { + $.get('/api/efficacy-tags', function(tags) { + const select = $('#herbInfoEfficacyFilter'); + select.empty().append(''); + + tags.forEach(tag => { + select.append(``); + }); + }); + } + + // 효능 태그 버튼 표시 + function loadEfficacyTagButtons() { + $.get('/api/efficacy-tags', function(tags) { + const container = $('#efficacyTagsContainer'); + container.empty(); + + // 카테고리별로 그룹화 + const grouped = {}; + tags.forEach(tag => { + if (!grouped[tag.category]) { + grouped[tag.category] = []; + } + grouped[tag.category].push(tag); + }); + + // 카테고리별로 표시 + Object.keys(grouped).forEach(category => { + const categoryHtml = ` +
+
${category}
+
+ ${grouped[category].map(tag => ` + + `).join('')} +
+
+ `; + container.append(categoryHtml); + }); + + // 태그 버튼 클릭 이벤트 + $('.efficacy-tag-btn').on('click', function() { + $(this).toggleClass('active'); + const selectedTags = $('.efficacy-tag-btn.active').map(function() { + return $(this).data('tag'); + }).get(); + + if (selectedTags.length > 0) { + searchByEfficacyTags(selectedTags); + } else { + loadAllHerbsInfo(); + } + }); + }); + } + + // 효능 태그로 검색 + function searchByEfficacyTags(tags) { + const queryString = tags.map(tag => `tags=${encodeURIComponent(tag)}`).join('&'); + $.get(`/api/herbs/search-by-efficacy?${queryString}`, function(herbs) { + displayHerbCards(herbs); + }); + } + + // 약재 정보 수정 (추후 구현) + function editHerbInfo(herbId) { + // herbId는 향후 수정 기능 구현시 사용 예정 + console.log('Edit herb info for ID:', herbId); + alert('약재 정보 수정 기능은 준비 중입니다.'); + // TODO: 정보 수정 폼 구현 + } +}); \ No newline at end of file diff --git a/templates/index.html.backup b/templates/index.html.backup new file mode 100644 index 0000000..5b03308 --- /dev/null +++ b/templates/index.html.backup @@ -0,0 +1,1578 @@ + + + + + + 한약 재고관리 시스템 + + + + + + + + +
+
+ + + + +
+ +
+

대시보드

+
+
+
+
총 환자수
+
0
+
+
+
+
+
재고 품목
+
0
+
+
+
+
+
오늘 조제
+
0
+
+
+
+
+
+ 재고 자산 + +
+
0
+ 전체 재고 +
+
+
+ +
+
+
+
+
최근 조제 내역
+
+
+ + + + + + + + + + + + + + +
조제일환자명처방명제수파우치상태
+
+
+
+
+
+ + +
+
+

환자 관리

+ +
+
+
+
+ +
+ + + + + + + + + + + + + + + +
환자명전화번호성별생년월일처방 횟수메모작업
+
+
+
+ + +
+
+

입고 관리

+
+ + +
+
+
입고장 목록
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + + + + + + + + + + + + + + +
입고일공급업체품목 수총 금액총 수량파일명작업
+
+
+ + +
+
+
새 입고 등록 (Excel 업로드)
+ +
+
+
+
+
+ + +
+
+ + +
+
+
+ Excel 형식: 한의사랑, 한의정보 (자동 감지)
+ Excel 내 업체명은 제조사(제약사)로 저장됩니다 +
+ +
+
+
+
+
+ + +
+
+

처방 관리

+ +
+
+
+ + + + + + + + + + + + + + +
처방코드처방명기본 첩수기본 파우치구성 약재작업
+
+
+
+ + +
+
+

조제 관리

+ +
+ + +
+
+
+
조제 내역
+
+ 오늘 조제: 0 + 이번달 조제: 0 +
+
+
+
+
+
+ +
+
+ +
+
+ + +
+
+
+ + + + + + + + + + + + + + + + + + + + + +
#조제일시환자명연락처처방명제수첩수파우치원가판매가상태처방전번호작업
+
+ +
+
+ + + +
+ + +
+
+

재고 현황

+
+ + + +
+
+ +
+
+
+
총 재고 금액
+

₩0

+
+
+
+
+
재고 보유 약재
+

0종

+
+
+
+
+
오늘 입고
+

0건

+
+
+
+
+
오늘 출고
+

0건

+
+
+
+ +
+
+
+ +
+
+ + + + + + + + + + + + + + + +
보험코드약재명현재 재고(g)로트 수평균 단가재고 금액작업
+
+
+
+ + + + + + + + + + + + +
+ + +
+
+

약재 관리 (주성분코드 기준)

+
+
+ + + +
+ +
+
+ + +
+ +
+ + +
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + + + +
주성분코드약재명효능재고량평균단가제품수상태작업
+
+
+
+ + +
+
+

한약재 정보 시스템

+
+ + + +
+
+ + +
+
+
+
+ + + +
+
+
+
+ + +
+
+
+
+ + + + + +
+ +
+ + + +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file