본문 바로가기

Study/class note

python / 커피키오스크 data add함수 따로 뺀 코드

# data add 함수 뺀 코드

class Coffee_Class():
    def __init__(self):
        self.image("c:\\data\\kioskimage.png")   # 이미지파일
        print('키오스크 시스템을 시작합니다.')
        
        # 메뉴 설정
        self.c_type = ['아메리카노','카페라떼','카페모카','녹차라떼']
        self.c_stock = [20,10,30,20]    # [0]: 아메리카노 재고, [1] : 카페라떼 재고, [2] : 카페모카 재고, [3] : 녹차라떼 재고
        self.c_price = [1500,2500,3500,3500]   # [0]: 아메리카노 가격, [1] : 카페라떼 가격, [2] : 카페모카 가격, [3] : 녹차라떼 가격
        self.coupon = 0
        self.order_no = 1
        self.cup = 0
        self.pay = 0
        
        # 주문데이터 설정
        self.cafe_dict = {}
        self.cafe_dict['주문번호'] = []
        self.cafe_dict['주문시간'] =[]
        self.cafe_dict['커피종류'] = []
        self.cafe_dict['수량'] = []
        self.cafe_dict['가격'] = []
    
    def image(self,name):    # 이미지 함수
        import PIL.Image as pilimg              
        import numpy as np                     
        import matplotlib.pyplot as plt

        im = pilimg.open(name)                
        pix = np.array(im)                      
        plt.imshow(pix)

        plt.axis('off')    #x,y축 없애기

        plt.show()     

    def machul_sum(self):    # 매출 정산하는 함수
        
        #현재 시간
        from datetime import datetime
        now = str(datetime.now())
        time = now[:10]+'일_'+now[11:13]+'시_'+now[14:16]+'분_'+now[17:19]+'초'     
        
        # 판다스 데이터 프레임 설정
        import pandas as pd
        cafe = pd.DataFrame(self.cafe_dict) 
        cafe.to_csv("c:\\data\\coffee_report_"+ time +".csv",encoding = "ANSI")        #판다스 dataframe 자동저장
        print('\n  오늘 지금까지 총 수익은 ',cafe['가격'].sum(),'원 입니다.')

        # 원형그래프 
        from matplotlib import font_manager, rc
        import matplotlib.pyplot as plt

        font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
        rc('font', family=font_name)    #폰트설정
        
        result = cafe.groupby('커피종류')['가격'].sum().reset_index()
        result.columns=['커피종류','총매출']
        result.plot.pie(y = '총매출',labels = result['커피종류'], startangle=100, autopct='%1.1f%%')
        plt.legend(loc='best',bbox_to_anchor=(1, 1))    #범례위치설정
        plt. title('커피종류별 총 매출액')       # 그래프 이미지 제목설정
        plt.savefig("c:\\data\\coffee_piechart_"+ time+".png")     #파이차트 이미지 자동저장

        return cafe
    
    def data_add(self,num):
        from datetime import datetime
        now = str(datetime.now())
        
        self.cafe_dict['주문번호'].append(self.order_no)
        self.cafe_dict['주문시간'].append(now)
        self.cafe_dict['커피종류'].append(self.c_type[num-1])
        self.cafe_dict['수량'].append(self.cup)
        self.cafe_dict['가격'].append(self.pay)
    
    def coffee_kiosk(self):
     
        #커피 이미지
        self.image("c:\\data\\coffee.png")       
        
        import pandas as pd

        while True:

            # 전체 품절
            if self.c_stock[0] == 0 and self.c_stock[1] == 0 and self.c_stock[2] == 0 and self.c_stock[3] == 0:
                print('\n\n\n모든 커피가 품절입니다.')
                print('='*40,'\n')
                break
                
            # 커피 메뉴판    
            self.image("c:\\data\\menu.jpg")    
            
            try:
                num = int(input('\n%d번손님,주문하시겠습니까? \n메뉴를 골라주세요. 번호를 눌러주세요.'%self.order_no))
            except:
                print('\n잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                continue
                
            # 주문
            if num < 5:
                print('%s를 선택하셨습니다.'%self.c_type[num-1])
                if self.c_stock[num-1] == 0:
                    print('\n%s : 품절'%self.c_type[num-1])
                    print('\n다시 입력해주세요~')
                    continue
                    
                try:
                    self.cup = int(input('몇 잔 주문하시겠습니까? '))
                except:
                    print('\n잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                    continue
                
                if self.cup > self.c_stock[num-1]:
                    print('\n죄송합니다. 주문량에 비해 %s가 부족합니다.'%self.c_type[num-1])
                    print('현재 주문 가능한 수량은 %d잔 입니다.' %self.c_stock[num-1], '다시 입력해주세요.')
                    
                    try:
                        self.cup = int(input('몇 잔 주문하시겠습니까? '))
                    except:
                        print('잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                        continue
                
                self.pay = self.c_price[num-1] * self.cup
                print('\n결제하실 금액은 %d원 입니다.'%self.pay)


                # 쿠폰x, 정상결제 시
                if self.coupon < 20:
                    
                    try:
                        money = int(input('돈을 입력하시오~ '))
                    except:
                        print('잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                        continue
                        
                    if money >= self.pay:
                        print('\n[주문번호 %d]'%self.order_no)
                        print('%s가 나왔습니다. 거스름돈은 '%self.c_type[num-1],money - self.pay,'원 입니다.')
                        print('쿠폰이 %d개 발급되었습니다.(20개 모으면 한잔 무료)'%self.cup)
                        self.c_stock[num-1] -= self.cup
                        self.coupon += self.cup
                        print('현재 보유한 쿠폰 :  %d개 '%self.coupon)
                        print('='*40,'\n')
                        
                        self.data_add(num)    # 데이터 쌓는 함수

                        self.order_no += 1

                    elif money < self.pay:
                        print('금액이 부족합니다. 돈을 반환합니다.')
                        print('='*40,'\n')
                        continue

                #쿠폰 20개 이상
                elif self.coupon >= 20:
                    
                    try:
                        question1 = int(input('쿠폰을 사용하시겠습니까?(1일 1회 1잔만 가능) \n예 : 1번\n아니오 : 2번 '))
                    except:
                        print('\n잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                        continue
                    
                    # 쿠폰사용 
                    if question1 == 1:
                        print('\n쿠폰 20개가 차감됩니다.')
                        self.coupon -= 20
                        if self.cup == 1:
                            self.pay -= self.pay
                            print('\n[주문번호 %d]'%self.order_no)
                            print('%s가 나왔습니다. 쿠폰은 발급되지 않습니다.'%self.c_type[num-1])
                            print('현재 보유한 쿠폰 :  %d개 '%self.coupon)
                            print('='*40,'\n')
                        else:
                            self.pay -= self.c_price[num-1]
                            
                            try:
                                money2 = int(input('결제할 차액은 %s 원 입니다. 돈을 입력하세요~ '%self.pay))
                            except:
                                print('\n잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                                continue
                            
                            if money2 >= self.pay:
                                print('\n[주문번호 %d]'%self.order_no)
                                print('%s가 나왔습니다. 거스름돈은 %s원 입니다. 쿠폰은 발급되지 않습니다.'%(self.c_type[num-1],money2 - self.pay))
                                print('현재 보유한 쿠폰 :  %d개 '%self.coupon)
                                print('='*40,'\n')

                            elif money2 < self.pay:
                                print('금액이 부족합니다. 돈을 반환합니다.')
                                print('='*40,'\n')
                                continue

                        self.data_add(num)    # 데이터 쌓는 함수

                        self.order_no += 1

                    #쿠폰 사용 안함
                    elif question1 == 2:
                        print('\n쿠폰을 사용하지 않습니다')
                        
                        try:
                            money = int(input('돈을 입력하시오~ '))
                        except:
                            print('\n잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                            continue
                        
                        if money >= self.pay:
                            print('\n[주문번호 %d]'%self.order_no)
                            print('%s가 나왔습니다. 거스름돈은 '%self.c_type[num-1],money - self.pay,'원 입니다.')
                            print('쿠폰이 %d개 발급되었습니다.(20개 모으면 한잔 무료)'%self.cup)
                            self.c_stock[num-1] -= self.cup
                            self.coupon += self.cup
                            print('현재 보유한 쿠폰 :  %d개 '%self.coupon)
                            print('='*40,'\n')

                            self.data_add(num)    # 데이터 쌓는 함수

                            self.order_no += 1

                        elif money < self.pay:
                            print('금액이 부족합니다. 돈을 반환합니다.')
                            print('='*40,'\n')
                            continue

                    else:
                        print('번호를 잘못 입력했습니다. 처음 화면으로 돌아갑니다.')


            # 결산(관리자용)         
            elif num == 10:
                print('\n\n------- 관리자 모드로 실행됩니다 -------')
                
                try:
                    password = int(input('비밀번호를 입력하세요~ '))
                except:
                    print('\n잘못된 값을 입력했습니다. 숫자를 입력하세요.\n처음 화면으로 돌아갑니다.')
                    continue
                
                if password == 1234:
                    print('\n정산 내역을 출력합니다')
                    break
                else:
                    print('비밀번호가 틀렸습니다. 처음 화면으로 돌아갑니다.')
                    continue

          # 메뉴 없음          
            else:
                print('메뉴가 없습니다. 처음 화면으로 돌아갑니다.')
                print('='*40,'\n')
                continue

        return self.machul_sum()
반응형