- 추후 웹프로젝트에 반영할 것을 전제로 Vscode에 파이썬을 작성하고 있음
2022.08.23 ~ 2022.08.26
<요구사항>
A. 제품관리시스템의 메뉴 중 '제품테이블 초기화' 메뉴 신설
1. 제품테이블(product)에 대한 초기화 작업 수행 직전의 모든 로우를 리스트로 보여줌.(목록조회와 동일)
2. '모두 삭제하고 초기화 하시겠습니까? y/n' 라고 출력하고 사용자에게 입력을 받아
y 인 경우에만 제품테이블(product)을 초기화
B. product 테이블에서 기존의 모든 로우를 지우고 아래와 똑같이 제품정보를 입력
C. 판매관리시스템의 메뉴 중 '판매테이블 초기화' 메뉴 신설
1. 판매테이블(sales)에 대한 초기화 작업 수행 직전의 모든 로우를 리스트로 보여줌.(목록조회와 동일)
2. '모두 삭제하고 초기화 하시겠습니까? y/n' 라고 출력하고 사용자에게 입력을 받아
y 인 경우에만 판매테이블(sales)을 초기화
D. sales 테이블에서 기존의 모든 로우를 지우고 아래와 똑같이 제품정보를 입력
E. 판매정보 수정 시 정상동작 확인
1. 판매테이블에서 제품판매수량을 임의로 수정하여 총 판매금액이 변경되는지 확인
1-1. 예를 들면 '나' 항에서 입력한 제품 중 a003 제품의 순번 4번의 정보를 보면 판매수량 1개이고 판매금액이 300이다.
이 판매수량을 3으로 바꾸었을 때 판매금액이 900으로 변경하는지 확인한다.
1-2. 1-1항과 같은 판매 수량 변경을 임의로 6개 이상 변경하고 수량변경에 따른 판매금액 변경을 확인하여 스샷
F. 외부파일을 읽어서 판매테이블에 저장
1. 판매관리시스템의 메뉴에 외부파일등록 메뉴 추가
1-1. 외부파일 등록메뉴의 기능 :
기존의 판매정보 등록 기능이 사용자 입력(input())으로 동작하는 것에 비해
텍스트 파일을 입력으로 하여 부적절한 데이터를 필터링 하고 적절한 데이터만을 sales테이블에 입력(insert)하는 기능
2. 주어진 sales_2.txt 파일을 읽어서 필터링
2-1. 첨부된 sales_2.txt파일을 읽어서 리스트로 저장
2-2. 리스트의 내용을 필터링
2-2-1. 년월일 정보에 오류가 있는지 확인하고 오류있는 자료는 판매테이블에 저장하는 대상에서 제외
2-2-2. 제품코드가 product테이블에 존재하지 않는 자료는 판매테이블에 저장하는 대상에서 제외
2-2-3. 텍스트 파일에는 판매수량만 존재함. 판매금액은 product 테이블의 단가(unitprice)를 이용하여 산출한 후에 저장
G. 시각화 결과물 도출
1. sales 테이블의 모든 정보를 차례로 읽어서 sales_all.txt 파일로 만듦.
1-1. 판매관리시스템의 메뉴에 '시각화출력' 메뉴 추가
1-2. '시각화출력' 메뉴의 기능은 필터링 거친 데이터로 그래프를 만드는 기능
2. sales_all.txt 파일을 읽어서 필터링
2-1. 필터링은 날짜 필터링 (윤년, 월, 일)을 수행
2-2. 판매금액 필터링 sales 테이블에 있는 수량(qty)과 product 테이블에 있는 단가(unitprice)에 의해 산출된
판매금액(amt)가 적절한지 필터링
3. sales 테이블의 모든 자료가 필터링을 통해 sales_all.txt 파일로 만들어진 것을 데이터프레임으로 생성
3-1. 이하의 과정을 수행함에 있어서 추가로 필요한 테이블이나 텍스트파일 등을
개별적으로 추가해서 만들어 코드에 활용해도 무방
3-2. 데이터프레임의 인덱스는 날짜, 제품코드 중 자유롭게 지정
3-3. 시각화 결과의 형태에 따라 인덱스가 다를 수 있음
4. 데이터프레임을 이용하여 예제의 시각화 결과물을 도출
4-1. 시각화 결과물을 예제는 다음과 같다.
4-1-1. 날짜 별 판매 금액 : 7월1일부터 8월 2일까지의 판매정보 중 제품구분 없이 날짜 별 총 합계를 보여줌
4-1-2. 모델 별 판매 금액 : 10개의 모델별로 모든 판매금액 합계를 보여줌
<Code Inspection>
1. 함수, 클래스 위치 정돈
2. 함수명, 클래스명, 메서드명 일관성 수립
3. 함수명, 클래스명, 메서드명 이해할 수 있도록 명명
(pep8 참고 - https://peps.python.org/pep-0008/)
<Test Case>
- 모든 요구사항이 충족되는지, 정상 실행되는지 확인해보라고 하셔서 테스트 케이스를 만드는게 좋을 것 같다고 생각함.
- 개인적으로 테스트케이스 폼을 만들어 작성하면서 요구사항 확인.
- Pass는 확인됨 / Fail은 실패 / N/A는 해당없음(또는 불가능) / Block은 보류(상위 레벨에서 N/A될 경우 등)
https://docs.google.com/spreadsheets/d/1_MwhApPPj6UrxOHeH1YCKrDM_84WKz5-YH2G196vI8A/edit?usp=sharing
Test Case
시트1 빅데이터분석_모의평가-4_답안지.zip Test Case (ver-1.0) Total,63,date of creation,22.09.02 Pass,69 Fail,0 Block,0 N/A,0 ID,사전조건,STEP1,STEP2,STEP3,오류발생시 출력,Result,비고 TC-001,config 딕셔너리 user, passwd, data
docs.google.com
<완성 코드>
- 전체적인 구성, 클래스 및 함수 생성 목적과 해당 유형으로 생성한 이유를 발표함
- 각자 자유롭게 함수와 클래스를 작성하였으나 나는 통일성을 가지는걸 원칙으로 함.
- 제품 판매 관리 시스템의 토대 완성
- https://drive.google.com/file/d/1sRizHngCU29rcATKrrnVUU0q7T4a9FTX/view?usp=sharing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 | import os import sys import pymysql # MySQL데이터베이스를 사용하기 위한 라이브러리를 등록함 import re # 정규식으로 문자를 필터링하기 위함 import datetime # 날짜 유효성 검사 위함 import pandas as pd # dataframe을 사용하기 위함 import matplotlib.pyplot as plt # 그래프 세부설정 및 팝업창 출력을 위함 config = { # MySQL데이터베이스를 사용하기 위해 환경변수를 딕셔너리로 생성함. 'host' : '127.0.0.1', # MySql 이 동작하는 ipv4주소 'user' : 'root', # MySql 설치할 때 정한 계정 'passwd' : 'root1234', # MySql 설치할 때 정한 비밀코드 'database' : 'test_db', # MySql 설치할 때 처음 생성한 데이터베이스 'port' : 3306, # MySql이 응용프로그램과 통신할 때 사용하는 포트코드 리터럴이 아닌 정수값으로 써야함 'charset' : 'utf8', # 한글을 사용하겠다는 설정 'use_unicode' : True # 한글을 사용하겠다는 설정 } from wcwidth import wcswidth # 한글이 포함된 문자열에 간격 맞추기 솔루션을 제공하는 라이브러리 def fmt(x, w, align='l'): """ 동아시아문자 폭을 고려하여, 문자열 포매팅을 해 주는 함수. w 는 해당 문자열과 스페이스문자가 차지하는 너비. align 은 문자열의 수평방향 정렬 좌/우/중간. """ x = str(x) l = wcswidth(x) s = w-l if s <= 0: return x if align == 'l': return x + ' '*s + '| ' # 공백 끝마다 구분선 '| ' 추가 if align == 'c': sl = s//2 sr = s - sl return ' '*sl + x + ' '*sr return ' '*s + x class ShowTables: def print_product(self, rows): print('{}{}{}{}'.format(fmt('pCode', 10), fmt('pName', 20), fmt('UnitPrice', 12), 'discountRate')) print('-'*60) for row in rows : print("{}{}{}{}".format(fmt(row[0], 10), fmt(row[1], 20), fmt(row[2], 12), row[3])) def print_sales(self, rows): print('{}{}{}{}{}'.format(fmt('seqNo', 6), fmt('sCode', 6), fmt('sDate', 20), fmt('Qty', 6), 'Amt')) print('-'*60) for row in rows : print("{}{}{}{}{}".format(fmt(row[0], 6), fmt(row[1], 6), fmt(row[2], 20), fmt(row[3], 6), row[4])) def print_sales_pname(self, rows): print('{}{}{}{}{}{}'.format(fmt('seqNo', 6), fmt('sCode', 6), fmt('pName', 20), fmt('sDate', 20), fmt('Qty', 6), 'Amt')) print('-'*80) for row in rows : print("{}{}{}{}{}{}".format(fmt(row[0], 6), fmt(row[1], 6), fmt(row[2], 20), fmt(row[3], 20), fmt(row[4], 6), row[5])) class Find: def __init__(self,table,find_sel,find_in_data=''): self.read_sel = find_sel # 메인함수의 메뉴 번호와 맞춤 # product 테이블 if table == 'p': if find_sel == 1 or find_sel == 3 or find_sel == 5 or find_sel == 6: self.find_sql = "select * from product where pCode =" + f"'{find_in_data}'" elif find_sel == 4 : self.find_sql = "select * from product where pName =" + f"'{find_in_data}'" else : self.find_sql = "select * from product" # sales 테이블 else : if find_sel == 1 or find_sel == 8: self.find_sql = "select * from product where pCode =" + f"'{find_in_data}'" elif find_sel == 3 : self.find_sql = "select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode =" + f"'{find_in_data}'" + "and S.sCode = P.pCode order by S.sDate desc" elif find_sel == 4 : self.find_sql = "select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where P.pName =" + f"'{find_in_data}'" + "and S.sCode = P.pCode;" elif find_sel == 5 or find_sel == 6 : self.find_sql = "select * from sales where sCode =" + f"'{find_in_data}'" elif find_sel == 7 or find_sel == 9: self.find_sql = "select * from sales" else : # sales 테이블과 product 테이블을 inner join하여 제품명을 표시하는 쿼리 self.find_sql = """select S.seqNo, S.sCode, P.pName, S.sDate, S.Qty, S.Amt from sales S, product P where S.sCode = P.pCode;""" def findall(self) : try : conn = pymysql.connect(**config) # 딕셔너리 config를 인수로 사용하여 conn 객체 생성 cursor = conn.cursor() # conn 객체로부터 cursor() 메소드를 호출하여 cursor 참조변수 생성 cursor.execute(self.find_sql) result = cursor.fetchall() return result # select 쿼리문의 실행 결과를 return함 # 쿼리의 실행결과가 없으면 요소의 갯수가 0인 리스트가 반환됨 except Exception as e : print('db 연동 실패 : ', e) conn.rollback() # 실행 취소 finally: cursor.close() conn.close() def findone(self) : try : conn = pymysql.connect(**config) # 딕셔너리 config를 인수로 사용하여 conn 객체 생성 cursor = conn.cursor() # conn 객체로부터 cursor() 메소드를 호출하여 cursor 참조변수 생성 cursor.execute(self.find_sql) result = cursor.fetchone() return result # select 쿼리문의 실행 결과를 return함 # 쿼리의 실행결과가 없으면 요소의 갯수가 0인 리스트가 반환됨 except Exception as e : print('db 연동 실패 : ', e) conn.rollback() # 실행 취소 finally: cursor.close() conn.close() class Read: target = '' target_name = '' def __init__(self, target, menu): self.target = target if self.target == 'p': self.target_name = '제품' else : self.target_name = '판매' # 메인의 메뉴 번호와 동일 if menu == 3: self.read_code() elif menu == 4: self.read_name() else : # 전체 조회 self.read_all() def read_all(self): f1 = Find(self.target, 2) rows = f1.findall() if rows: print('\n<<<목록 조회입니다>>>') print('===테이블 조회 1===') st1 = ShowTables() if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) else: print('출력할 데이터가 없습니다.') def read_code(self): st1 = ShowTables() f1 = Find(self.target, 2) rows = f1.findall() if rows: print('\n<<<전체 목록 조회>>>') if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) print('\n<<<개별 조회(코드)입니다>>>') in_Code = input('조회할 코드를 입력하세요 : ') f2 = Find(self.target, 3, in_Code) rows = f2.findall() if rows: print('\n===테이블 조회 2(코드)===') if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) else: print(f'입력하신 코드에 해당하는 {self.target_name}이(가) 없습니다.') def read_name(self): st1 = ShowTables() f1 = Find(self.target, 2) rows = f1.findall() if rows: print('\n<<<전체 목록 조회>>>') if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) print(f'\n<<<개별 조회({self.target_name}명)입니다>>>') in_pName = input('조회할 제품명을 입력하세요 : ') f1 = Find(self.target, 4, in_pName) rows = f1.findall() if rows: print(f'\n===테이블 조회 2({self.target_name}명)===') if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) else: print(f'입력하신 제품명에 해당하는 {self.target_name}이(가) 없습니다.') class InputFilter: def __init__(self): self.inputValueFilter_result = False self.pname = '' self.uprice = '' self.drate = '' self.qty = '' self.date = '' # def set_pname(self, pname) : if pname == '' or len(pname) < 0 : print("공백은 입력 불가능합니다.") self.inputValueFilter_result = False else: self.inputValueFilter_result = True self.pname = pname return self.inputValueFilter_result # def set_uprice(self, uprice) : if uprice == '' or len(uprice) < 0 : print("공백은 입력 불가능합니다.") self.inputValueFilter_result = False elif uprice.isdigit() == False: # 정수만 입력 가능 # 사은품같은 0원제품도 있을 수 있어 0 입력시 오류 출력 안함 print('숫자로만 입력해주세요.') self.inputValueFilter_result = False else: self.inputValueFilter_result = True self.uprice= uprice return self.inputValueFilter_result # def set_drate(self, drate) : if drate == '' : print("1.0으로 입력됩니다.") self.inputValueFilter_result = True self.drate = '1.0' return self.inputValueFilter_result try : drate = float(drate) except : print("실수만 입력 가능합니다.") self.inputValueFilter_result = False return self.inputValueFilter_result # 해당 컬럼은 default값이 있기 때문에 공백 입력 가능 if 0 > drate or 100 < drate: # 퍼센트이기 때문에 0~100 사이의 값만 입력 가능 print('0부터 100까지의 수만 입력 가능합니다.') self.inputValueFilter_result = False else: self.inputValueFilter_result = True self.drate= drate return self.inputValueFilter_result # def set_qty(self, qty) : if qty == '' or len(qty) < 0 : print("\n공백은 입력 불가능합니다.") self.inputValueFilter_result = False elif qty.isdigit() == False: # 정수만 입력 가능 print('\n숫자로만 입력해주세요.') self.inputValueFilter_result = False elif int(qty) < 1: print("\n1개부터 판매가능합니다.") self.inputValueFilter_result = False else: self.inputValueFilter_result = True self.qty = qty return self.inputValueFilter_result def set_date(self, date) : if date == '' or len(date) < 0 : print("\n내용을 입력하지 않으시면 현재 날짜로 등록됩니다.") self.date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') print(self.date, type(self.date)) self.inputValueFilter_result = True elif bool(re.match(r'\d{4}-\d{2}-\d{2}', date)): # %Y-%m-%d 형태로 입력되었을 때 try: datetime.datetime.strptime(date, "%Y-%m-%d") print("\n날짜만 입력하셔서 시간은 00:00:00으로 등록됩니다.") self.date = date + " 00:00:00" self.inputValueFilter_result = True except: print("\n존재할 수 없는 날짜입니다.") self.inputValueFilter_result = False elif bool(re.match(r'\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}', date)): # %Y-%m-%d %H:%M:%S 형태로 입력되었을 때 try: datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') self.date = date self.inputValueFilter_result = True except: print("\n존재할 수 없는 날짜 또는 시간입니다.") self.inputValueFilter_result = False else: self.inputValueFilter_result = True self.date = date return self.inputValueFilter_result class UserInput: # 사용자 입력 함수 def input_product(self): if1 = InputFilter() while True: if if1.set_pname(input("제품 이름을 입력하세요 : ")) : in_pname = if1.pname break else: continue # while True: if if1.set_uprice(input("가격을 입력하세요 : ")) : in_uprice = if1.uprice break else: continue # while True: if if1.set_drate(input("할인율을 입력하세요 : ")) : in_drate = if1.drate break else: continue # return in_pname, in_uprice, in_drate def input_sales(self): if1 = InputFilter() # 필터링 클래스 생성 while True: if if1.set_qty(input("판매 수량을 입력하세요 : ")) : in_qty = if1.qty break else: continue while True: if if1.set_date(input("날짜를 0000-00-00 00:00:00 형식으로 입력하세요 : ")) : in_date = if1.date break return in_qty, in_date class Insert: target = '' target_name = '' def __init__(self, target): self.target = target if self.target == 'p': self.target_name = '제품' else : self.target_name = '판매' self.insert() def insert(self): try : conn = pymysql.connect(**config) # 딕셔너리 config를 인수로 사용하여 conn 객체 생성 cursor = conn.cursor() # conn 객체로부터 cursor() 메소드를 호출하여 cursor 참조변수 생성 # print(f"\n<<<{self.target_name} 등록입니다>>>") in_Code = input("등록할 제품코드를 입력하세요 : ") if in_Code != '' : f1 = Find(self.target, 1, in_Code) # 입력받은 코드가 제품 테이블에 존재하는지 확인 if self.target == 'p': self.insert_product(f1.findall(), in_Code, cursor, conn) else : self.insert_sales(f1.findall(), in_Code, cursor, conn) else : print(f"{self.target_name} 등록을 위해 올바른 제품코드를 입력해 주세요") except Exception as e : print('오류 : ', e) conn.rollback() # 실행 취소 finally: cursor.close() conn.close() def insert_product(self, find_rows, in_pCode, cursor, conn): if len(find_rows) : # product 테이블에 존재하는 pCode일 경우 print("이미 존재합니다. 다른 제품코드를 입력하세요") else : ui1 = UserInput() iValue = ui1.input_product() # sql = f"""insert into product values('{in_pCode}','{iValue[0]}', '{iValue[1]}', '{iValue[2]}')""" cursor.execute(sql) conn.commit() print("\n제품등록을 성공했습니다.") print() def insert_sales(self, find_rows, in_sCode, cursor, conn): if len(find_rows) == 0 : # product 테이블에 존재하지 않는 sCode일 경우 print("조회결과 입력한 코드에 맞는 제품이 없습니다.") yesNo = input('제품을 추가하시겠습니까?(y/n) : ') if yesNo == "y" or yesNo == "Y": print('\n<<<제품 추가 등록입니다>>>') self.insert_product(find_rows, in_sCode, cursor, conn) # 추가 등록 후 다시 판매 등록 print('<<<판매 등록입니다>>>') f1 = Find(self.target, 1, in_sCode) self.insert_sales(f1.findall(), in_sCode, cursor, conn) else : print("판매등록을 종료합니다.") else: ui1 = UserInput() iValue = ui1.input_sales() # sql = f"""insert into sales(sCode, sDate, Qty, Amt) select '{in_sCode}', '{iValue[1]}', '{iValue[0]}', {iValue[0]} * unitPrice from product where pCode = '{in_sCode}';""" cursor.execute(sql) conn.commit() print("\n판매등록을 성공했습니다.") print() class Update: target = '' target_name = '' def __init__(self, target): self.target = target if target == 'p': self.target_name = '제품' else : self.target_name = '판매' self.update() def update(self): print(f"<<<{self.target_name} 목록 조회입니다>>>") f1 = Find(self.target, 2) rows = f1.findall() st1 = ShowTables() if self.target == 'p': st1.print_product(rows) else : st1.print_sales_pname(rows) # try : conn = pymysql.connect(**config) # 딕셔너리 config를 인수로 사용하여 conn 객체 생성 cursor = conn.cursor() # conn 객체로부터 cursor() 메소드를 호출하여 cursor 참조변수 생성 # print(f'\n<<<{self.target_name} 수정입니다>>>') in_Code = input('수정할 제품코드를 입력하세요 : ') if in_Code != '': f2 = Find(self.target, 5, in_Code) # 입력받은 코드가 타겟 테이블에 존재하는지 확인 if self.target == 'p': self.update_product(f2.findall(), in_Code, cursor, conn) else : self.update_sales(f2.findall(), in_Code, cursor, conn) else : # select 쿼리 실행결과가 없는 경우 print('수정할 제품코드를 입력해주세요.') except Exception as e : print('db 연동 실패 : ', e) conn.rollback() # 실행 취소 finally: cursor.close() conn.close() def update_product(self, find_rows, in_pCode, cursor, conn): if len(find_rows) == 0: # 입력받은 코드가 제품 테이블에 없을 경우 print("조회결과 입력한 코드에 맞는 제품이 없습니다.") # else : # select 쿼리 실행결과가 있는 경우 print("\n<<<제품코드 조회결과입니다>>>") st1 = ShowTables() st1.print_product(find_rows) yesNo = input('수정하시겠습니까?(y/n) : ') if yesNo == "y" or yesNo == "Y": print("<<<수정할 내용을 입력하세요.>>>") ui1 = UserInput() iValue = ui1.input_product() sql = f"update product set pName = '{iValue[0]}', unitPrice ='{iValue[1]}', discountRate='{iValue[2]}' where pCode = '{in_pCode}'" cursor.execute(sql) # sql문 실행 conn.commit() print("<<<수정을 완료했습니다>>>") print("\n<<<수정 결과입니다>>>") f1 = Find('p', 5, in_pCode) st1.print_product(f1.findall()) else: print("<<<수정을 취소했습니다.>>>") def update_sales(self, find_rows, in_sCode, cursor, conn): ls_seqNo = [] st1 = ShowTables() if len(find_rows) == 0: # 입력받은 코드가 판매 테이블에 없을 경우 print("조회결과 입력한 코드에 맞는 판매가 없습니다.") # else: print("\n<<<제품코드 조회결과입니다>>>") st1.print_sales(find_rows) for row in find_rows: ls_seqNo.append(str(row[0])) # 입력받은 i_seqNo와 비교하기 위해 str로 형변환 # 아래 if문을 if int(i_seqNo) in ls_seqno:로 수정할 경우 # int값이 아닌 값을 입력받았을 때 예외처리를 추가로 해주어야 함. # 그래서 str(row[0])으로 리스트 내부 값들을 str형으로 변환하여 예외처리를 할 필요가 없도록 함. i_seqNo = input("수정할 판매번호를 입력하세요 : ") # sales 테이블의 primary key는 (seqNo, sCode)이므로 seqNo 또한 입력받음. if i_seqNo in ls_seqNo: yesNo = input('수정하시겠습니까?(y/n) : ') if yesNo == "y" or yesNo == "Y": print("<<<수정할 내용을 입력하세요.>>>") ui1 = UserInput() iValue = ui1.input_sales() sql = f"""update sales set sDate = now(), Qty = '{iValue[0]}', Amt ='{iValue[0]}' * (select unitPrice from product where pCode='{in_sCode}') where seqNo = '{i_seqNo}' and sCode = '{in_sCode}'""" # 테이블에 update시 sDate를 수정한 날짜로 변경하기 위해 now() 함수 활용 cursor.execute(sql) # sql문 실행 conn.commit() print("<<<수정을 완료했습니다>>>") print("\n<<<수정 결과입니다>>>") f1 = Find('s', 5, in_sCode) st1.print_sales(f1.findall()) else: print("<<<수정을 취소했습니다.>>>") else: print("<<<없는 판매번호입니다. 수정을 종료합니다.>>>") class Delete: # update 테이블과 거의 유사한 구조이지만, 코드 가독성 향상과 # 기능별 분리를 위해 별도의 클래스로 분리함. target = '' target_name = '' def __init__(self, target): self.target = target if target == 'p': self.target_name = '제품' else : self.target_name = '판매' self.delete() def delete(self): print(f"<<<{self.target_name} 목록 조회입니다>>>") f1 = Find(self.target, 2) find_rows = f1.findall() st1 = ShowTables() if self.target == 'p' : st1.print_product(find_rows) else : st1.print_sales_pname(find_rows) # try : conn = pymysql.connect(**config) # 딕셔너리 config를 인수로 사용하여 conn 객체를 만듬. cursor = conn.cursor() # conn 객체로부터 cursor() 메소드를 호출하여 cursor 참조변수를 만듬. # print(f"\n<<<{self.target_name} 삭제입니다>>>") in_Code = input('삭제할 제품코드를 입력하세요 : ') if in_Code != '': f2 = Find(self.target, 6, in_Code) # 입력받은 코드가 타겟 테이블에 존재하는지 확인 if self.target == 'p': self.delete_product(f2.findall(), in_Code, cursor, conn) else : self.delete_sales(f2.findall(), in_Code, cursor, conn) else : print('삭제할 제품코드를 입력해주세요.') except Exception as e : print('db 연동 실패 : ', e) conn.rollback() # 실행 취소 finally: cursor.close() conn.close() def delete_product(self, find_rows, in_pCode, cursor, conn): if len(find_rows) == 0 : print(f"조회결과 입력한 코드에 맞는 제품이 없습니다.") # else : st1 = ShowTables() yesNo = input('삭제하시겠습니까?(y/n) : ') if yesNo == "y" or yesNo == "Y": sql = f"delete from product where pCode = '{in_pCode}'" cursor.execute(sql) # sql문 실행 conn.commit() print('삭제 성공했습니다.') print("\n<<<목록 조회입니다>>>") f3 = Find(self.target, 2) find_rows = f3.findall() if self.target == 'p' : st1.print_product(find_rows) else : st1.print_sales_pname(find_rows) else : print("<<<삭제를 취소했습니다.>>>") def delete_sales(self, find_rows, in_sCode, cursor, conn): ls_seqNo = [] st1 = ShowTables() if len(find_rows) == 0 : print(f"조회결과 입력한 코드에 맞는 판매가 없습니다.") # else : print("\n<<<제품코드 조회결과입니다>>>") st1.print_sales(find_rows) for row in find_rows: ls_seqNo.append(str(row[0])) i_seqNo = input("수정할 판매번호를 입력하세요 : ") if i_seqNo in ls_seqNo: yesNo = input('삭제하시겠습니까?(y/n) : ') if yesNo == "y" or yesNo == "Y": sql = f"delete from sales where sCode = '{in_sCode}' and seqNo = '{i_seqNo}'" cursor.execute(sql) # sql문 실행 conn.commit() print('삭제 성공했습니다.') print("\n<<<목록 조회입니다>>>") f3 = Find(self.target, 2) rows = f3.findall() if self.target == 'p' : st1.print_product(rows) else : st1.print_sales_pname(rows) else : print("<<<삭제를 취소했습니다.>>>") else : print("<<<없는 판매번호입니다. 삭제를 종료합니다.>>>") class Reset: target = '' target_name = '' def __init__(self, target): self.target = target if self.target == 'p': self.target_name = 'product' else : self.target_name = 'sales' self.reset() def reset(self): # 테이블 전체 출력 st1 = ShowTables() f1 = Find(self.target, 7) find_rows = f1.findall() if find_rows : if self.target == 'p' : st1.print_product(find_rows) else : st1.print_sales(find_rows) print(f'\n<<<{self.target_name}테이블 초기화입니다>>>') yesNo = input('모두 삭제하고 초기화 하시겠습니까?(y/n) : ') if yesNo == "y" or yesNo == "Y": try: conn = pymysql.connect(**config) cursor = conn.cursor() # 전체 내용 삭제 sql = f"delete from {self.target_name}" cursor.execute(sql) conn.commit() # 대상이 sales 테이블일경우 seqNo가 1부터 시작되도록 초기화 if self.target == 's' : sql = "alter table sales auto_increment = 1" cursor.execute(sql) conn.commit() print("초기화 성공했습니다.") except Exception as e : print('db 연동 실패 : ', e) conn.rollback() # 실행 취소 finally: cursor.close() conn.close() else : print("<<<초기화를 취소했습니다.>>>") else : print("삭제할 데이터가 없습니다.") print("<<<초기화를 취소합니다.>>>") class FileRW : def read_file(self, file_name): try: tf1 = open(file_name, mode='r', encoding='utf-8') # 파일을 읽기 모드로 열고, 한글이 깨지지 않도록 utf-8로 인코딩 full_text = tf1.readlines() # 파일을 한줄씩 읽어 list변수 full_text에 저장 for i in range(len(full_text)): full_text[i] = full_text[i].strip() # 파일 내용의 맨 앞과 맨 뒤의 공백을 제거함 full_text[i] = full_text[i].split(',') # 콤마를 기준으로 분리하여 2차원 리스트로 저장 tf1.close() return full_text except Exception : print('없는 파일명입니다. 확장자를 잊지는 않으셨나요?') full_text = False finally : return full_text def write_file(self, file_name, rows): try: tf1 = open(file_name, mode='w', encoding='utf-8') # 파일을 읽기 모드로 열고, 한글이 깨지지 않도록 utf-8로 인코딩 for row in rows: text = ','.join(str(i) for i in row) # 각 요소를 str형으로 변환한 후 ,를 구분자로 하여 한줄로 만듦 tf1.write(text + '\n') # 파일에 쓰기 except Exception as e : print('파일 쓰기 중 에러가 발생했습니다.') finally : tf1.close() class FileFilter: def filter_code(self, content): ls_code = [] rm_code = [] for i in range(len(content)): ls_code.append(content[i][0]) for code in ls_code : f1 = Find('s', 8, code) row = f1.findone() # product 테이블에 존재하는지만 확인하면 되므로 한줄만 읽어옴 if row == None: rm_code.append(ls_code.index(code)) # 지워야 하는 코드의 인덱스를 리스트 rm_code에 저장 pop = 0 # 삭제 후 인덱스를 조정해주기 위한 변수 for i in rm_code : del content[i-pop] pop = pop+1 # 삭제 대상 인덱스 삭제 후 뒤의 항목들은 # 인덱스가 1씩 감소하기 때문에 pop을 증가시켜 인덱스에서 마이너스해준다. return content def filter_file_date(self, content): ls_date = [] rm_date = [] for i in range(len(content)): ls_date.append(content[i][1]) for date in ls_date: try: str_date = date[0:4] + '-' + date[4:6] + '-' + date[6:8] datetime.datetime.strptime(str_date, "%Y-%m-%d") except Exception as e : # 존재 가능한 날짜가 아닐 경우 rm_date.append(ls_date.index(date)) # 지워야 하는 날짜의 인덱스를 리스트 rm_date에 저장 if rm_date : pop = 0 for i in rm_date : del content[i-pop] pop = pop+1 # 삭제 대상 인덱스 삭제 후 뒤의 항목들은 # 인덱스가 1씩 감소하기 때문에 pop을 증가시켜 인덱스에서 마이너스해준다. return content def filter_table_date(self, content): ls_date = [] rm_date = [] for i in range(len(content)): ls_date.append(content[i][2]) for i in range(len(ls_date)): try: datetime.datetime.strptime(ls_date[i], '%Y-%m-%d %H:%M:%S') content[i][2] = ls_date[i][0:10] # 리스트에는 시간을 제외한 날짜만 저장되도록 함 except Exception as e : # 존재 가능한 날짜가 아닐 경우 rm_date.append(i) # 지워야 하는 날짜의 인덱스를 리스트 rm_date에 저장 if rm_date : pop = 0 for i in rm_date : del content[i-pop] pop = pop+1 # 삭제 대상 인덱스 삭제 후 뒤의 항목들은 # 인덱스가 1씩 감소하기 때문에 pop을 증가시켜 인덱스에서 마이너스해준다. return content def filter_amt(self, content): try : conn = pymysql.connect(**config) cursor = conn.cursor() # 딕셔너리 config를 인수로 한 커넥션 객체 생성 및 커서 참조변수 생성 for con in content: sql = f"select unitPrice from product where pCode = '{con[1]}'" cursor.execute(sql) price = cursor.fetchone() price = price[0] if float(con[4]) != float(int(con[3]) * price): con[4] = int(con[3]) * price # 곱의 결과가 리스트 내부의 amt(con[4])와 같지 않을 경우 # con[4]에 곱한 결과를 덮어씌움 except Exception as e : print('product 테이블의 unitprice 조회에 실패했습니다.') conn.rollback() # 실행 취소 finally: cursor.close() conn.close() return content class FileInsert: target = '' target_name = '' file_name = '' def __init__(self, target): self.target = target if target == 's' : self.target_name == '제품' else : self.target_name = '판매' self.file_insert() def file_insert(self): print(f'\n<<<{self.target_name}테이블에 외부 파일 등록입니다>>>') self.file_name = input("data 폴더 내부에 있는 파일명을 입력하세요 : ") self.file_name = 'data/'+self.file_name fr1 = FileRW() content = fr1.read_file(self.file_name) if content == False: print('<<<외부 파일 등록을 종료합니다>>>') else : ff1 = FileFilter() lines = ff1.filter_code(content) lines = ff1.filter_file_date(lines) lines = self.set_amt(lines) self.write_table(lines) print('<<<테이블에 등록이 완료되었습니다.>>>') def set_amt(self, content): for line in content : f1 = Find('s', 8, line[0]) row = f1.findall()[0] if len(line) > 3: # 인덱스3 (가격)이 이미 있다면 지워줌 del line[3] line.append(int(row[2]) * int(line[2])) # 각 항목의 제품코드를 활용하여 product 테이블에서 unitPrice를 가져와 # qty(인덱스2)와 곱하여 리스트 각 항목 끝에 삽입한다. return content def write_table(self, full_text): try : conn = pymysql.connect(**config) cursor = conn.cursor() # 딕셔너리 config를 인수로 한 커넥션 객체 생성 및 커서 참조변수 생성 for text in full_text: date = text[1][0:4] + '-' + text[1][4:6] + '-' + text[1][6:8] date = datetime.datetime.strptime(date, '%Y-%m-%d') sql = f"""insert into sales(sCode, sDate, Qty, Amt) values ('{text[0]}', '{date}', '{text[2]}', '{text[3]}')""" cursor.execute(sql) conn.commit() # product 테이블에 존재하는지만 확인하면 되므로 한줄만 읽어옴 except Exception as e : print('테이블에 insert 실패 : ', e) conn.rollback() # 실행 취소 finally: cursor.close() conn.close() class ShowGraphs: target = '' target_name = '' def __init__(self, target): self.target = target if target == 's' : self.target_name == '제품' else : self.target_name = '판매' self.show_amt_graph() def show_amt_graph(self): f1 = Find('s', 9) rows = f1.findall() # 테이블 전체를 읽어서 fr1 = FileRW() # 파일에 쓰기 함. fr1.write_file('sales_all.txt', rows) content = fr1.read_file('sales_all.txt') # 파일을 다시 읽어옴. ff1 = FileFilter() lines = ff1.filter_table_date(content) # 날짜 필터링 lines = ff1.filter_amt(lines) # amt 필터링 lines = self.add_column(lines, 'pName', 2) # 리스트에 pName 추가 lines = self.add_column(lines, 'unitPrice', 5) # 리스트에 unitPrice 추가 column_names = ['seqNo', 'pCode', 'pName', 'date', 'qty', 'unitPrice', 'amt'] df = pd.DataFrame(lines, columns=column_names) # 데이터프레임 생성 df = df.set_index('date') df['amt'] = pd.to_numeric(df['amt']) # 문자인 amt 컬럼을 숫자로 변경 self.create_graph(df, 'date') self.create_graph(df, 'pName') def add_column(self, content, col_name, location): try : conn = pymysql.connect(**config) cursor = conn.cursor() # 딕셔너리 config를 인수로 한 커넥션 객체 생성 및 커서 참조변수 생성 for con in content: sql = f"select {col_name} from product where pCode = '{con[1]}'" cursor.execute(sql) data = str(cursor.fetchone()) data = re.sub("['(),]", '', data) # re.sub 메서드를 통해 데이터 주변의 문자 제거 con.insert(location, str(data)) except Exception as e : print(f'product 테이블의 {col_name} 조회에 실패했습니다.') conn.rollback() # 실행 취소 finally: cursor.close() conn.close() return content def create_graph(self, df, group_col_name): sub_df = pd.DataFrame() plt.rc('font', family='Malgun Gothic') if group_col_name == 'date': sub_df['amt'] = df.amt # 인덱스와 amt 컬럼을 가진 df_day 데이터프레임 생성 sub_df = sub_df.groupby(group_col_name).sum() # 날짜별 합계를 데이터프레임으로 저장 sub_df.plot.line(figsize=(10, 5)) plt.xlabel('date') plt.legend(['total amount']) else : sub_df[group_col_name] = df[group_col_name] sub_df['amt'] = df.amt sub_df = sub_df.groupby(group_col_name).sum() # 날짜별 합계를 데이터프레임으로 저장 sub_df = sub_df.sort_values('amt', ascending=False) # 총액이 낮은순으로 정렬 sub_df.plot.barh(figsize=(10, 5)) plt.xlabel('total amount') plt.ylabel(group_col_name) path = 'data/'+group_col_name+'.png' plt.savefig(path) # 파일로 저장 plt.show() # 팝업창으로 출력 if __name__ == "__main__" : while True: os.system('cls') print("-----제품관리-----") print("제품 등록 : 01 ") print("제품목록 조회 : 02 ") print("코드별 조회 : 03 ") print("제품명별 조회 : 04 ") print("제품 수정 : 05 ") print("제품 삭제 : 06 ") print("테이블 초기화 : 07 ") print("\n-----판매관리-----") print("판매 등록 : 11 ") print("판매목록 조회 : 12 ") print("코드별 조회 : 13 ") print("제품명별 조회 : 14 ") print("판매 수정 : 15 ") print("판매 삭제 : 16 ") print("테이블 초기화 : 17 ") print("외부파일 등록 : 18 ") print("시각화 출력 : 19 ") print() print('------------------') print("관리 종료 : 00 ") print('------------------') print() sel = input("작업을 선택하세요 : ") print() if sel == '01' : p1 = Insert('p') os.system("pause") elif sel == '02' : p2 = Read('p', 2) os.system("pause") elif sel == '03' : p3 = Read('p', 3) os.system("pause") elif sel == '04' : p4 = Read('p', 4) os.system("pause") elif sel == '05' : p5 = Update('p') os.system("pause") elif sel == '06' : p6 = Delete('p') os.system("pause") elif sel == '07' : p7 = Reset('p') os.system("pause") # elif sel == '11' : s1 = Insert('s') os.system("pause") elif sel == '12' : s2 = Read('s', 2) os.system("pause") elif sel == '13' : s3 = Read('s', 3) os.system("pause") elif sel == '14' : s4 = Read('s', 4) os.system("pause") elif sel == '15' : s5 = Update('s') os.system("pause") elif sel == '16' : s6 = Delete('s') os.system("pause") elif sel == '17' : s7 = Reset('s') os.system("pause") elif sel == '18' : s8 = FileInsert('s') os.system("pause") elif sel == '19' : s0 = ShowGraphs('s') os.system("pause") # elif sel == '00' : print("직원관리를 종료합니다. ") os.system("pause") os.system('cls') sys.exit(0) else : print("잘못 선택했습니다. ") os.system("pause") | cs |
'web project' 카테고리의 다른 글
제품&판매 관리 시스템 : 삭제, 수정 히스토리 테이블 생성 및 관리 (0) | 2022.10.05 |
---|---|
제품&판매 관리 시스템 : 포트폴리오 수정, 시스템 관련 질답 (0) | 2022.10.05 |
제품&판매 관리 시스템 : change log 작성, 포트폴리오 ppt (0) | 2022.10.04 |
제품&판매 관리 시스템 : 비교 분석, 벤치마킹을 통한 코드 개선 (0) | 2022.09.30 |
제품&판매 관리 시스템 : 테이블 생성, 체크리스트, 1차 코드 (0) | 2022.09.29 |
댓글