renix1

Simple bank in cli

Jan 5th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.60 KB | None | 0 0
  1. import os
  2. import sys
  3. import time
  4. import random
  5.  
  6. class ClearScreen:
  7.     def __call__(self):
  8.         if sys.platform.startswith('win32'):
  9.             os.system('cls')
  10.         elif sys.platform.startswith('darwin'):
  11.             os.system('clear')
  12.         elif sys.platform.startswith('cygwin') or sys.platform.startswith('linux'):
  13.             os.system('clear')
  14.         else:
  15.             print('Trying clear', end='')
  16.             for i in range(10):
  17.                 sys.stdout.write('.')
  18.                 sys.stdout.flush()
  19.                 time.sleep(.010)
  20.             os.system('clear')
  21. clear = ClearScreen()
  22.  
  23. class Cliente:
  24.     def __init__(self, nome, cpf, rg, data_nascimento, telefone, endereco, dinheiro=0):
  25.         self.__id = self.gerar()
  26.         self.__conta = self.gerar()
  27.         self.__senha = self.gerar()
  28.         self.nome = nome
  29.         self.__cpf = cpf
  30.         self.__rg = rg
  31.         self.__data_nasc = data_nascimento
  32.         self.__tel = telefone
  33.         self.__end = endereco
  34.         self.__din = dinheiro
  35.  
  36.     @staticmethod
  37.     def gerar():
  38.         """
  39.            GERA UM NÚMERO ALEATÓRIO PARA SER UTILIZADO POR VARIÁVEIS ACIMA
  40.        """
  41.         return(random.randint(0, 10**10))
  42.  
  43.     def validar_dados(self):
  44.         """
  45.            AQUI VALIDAMOS OS DADOS DE FORMA RÁPIDA E SIMPLES
  46.            NÃO HÁ VERIFICAÇÃO SE O CPF É VÁLIDO OU NÃO, ETC.
  47.        """
  48.         v_cpf = len(self.__cpf) == 11
  49.         v_data_nasc = len(self.__data_nasc.replace('/', '')) == 6 or len(self.__data_nasc.replace('/', '')) == 8
  50.         v_tel = len(self.__tel.replace('-', '')) == 8 or len(self.__tel.replace('-', '')) == 9 \
  51.         or len(self.__tel.replace('-', '')) == 10 or len(self.__tel.replace('-', '')) == 11
  52.         v_end = self.__end.upper().startswith('R') or self.__end.upper().startswith('RUA') \
  53.         or self.__end.upper().startswith('AV') or self.__end.upper().startswith('AVENIDA')
  54.         count = 0
  55.         for i in [v_cpf, v_end, v_data_nasc, v_tel]:
  56.             if i == True:
  57.                 count += 1
  58.         return True if count == 4 else False
  59.  
  60.     def acessar_banco(self):
  61.         """
  62.            O ACESSO DE TODO USUÁRIO DO BANCO PASSARÁ POR AQUI
  63.        """
  64.         nome, conta, agencia = self.consultar_dados()
  65.         print("Usuário: %s\nConta: %d\nAgência: %d\n" % (nome, conta, agencia))
  66.         escolha = int(input("[1] - Sacar dinheiro\n[2] - Ver extrato\n[3] - Depositar\n[4] - Sair\nentrada: "))
  67.         print()
  68.         if escolha == 1:
  69.             print('Entrando na seção para sacar dinheiro', end='')
  70.             for i in range(30):
  71.                 sys.stdout.write('.')
  72.                 sys.stdout.flush()
  73.                 time.sleep(.009)
  74.             else:
  75.                 print()
  76.                 self.sacar()
  77.         elif escolha == 2:
  78.             print('Acessando extrato', end='')
  79.             for i in range(30):
  80.                 sys.stdout.write('.')
  81.                 sys.stdout.flush()
  82.                 time.sleep(.009)
  83.             else:
  84.                 print()
  85.                 self.extrato()
  86.         elif escolha == 3:
  87.             print('Acessando área para depósito em conta', end='')
  88.             for i in range(30):
  89.                 sys.stdout.write('.')
  90.                 sys.stdout.flush()
  91.                 time.sleep(.009)
  92.             else:
  93.                 print()
  94.                 self.depositar()
  95.         else:
  96.             print('Saindo do sistema', end='')
  97.             for i in range(25):
  98.                 sys.stdout.write('.')
  99.                 sys.stdout.flush()
  100.                 time.sleep(.009)
  101.             else:
  102.                 sys.exit(0)
  103.  
  104.     def sacar(self):
  105.         """    
  106.            FUNÇÃO FEITA PRA SACAR DINHEIRO DO CLIENTE
  107.        """
  108.         ced_100, ced_50, ced_20, ced_10, ced_5, ced_2 = 0, 0, 0, 0, 0, 0
  109.         quantias = [self.__din//5, self.__din//2.5, self.__din//2]
  110.         escolhas = print("1 - %d\n2 - %d\n3 - %d\n"  % (quantias[0], quantias[1], quantias[2]))
  111.         quantia = int(input("Digite a quantia: "))
  112.         quantia = quantias[quantia-1]
  113.         if quantia in quantias:
  114.             while quantia >= 100:
  115.                 ced_100 += 1
  116.                 quantia -= 100
  117.             while quantia >= 50:
  118.                 ced_50 += 1
  119.                 quantia -= 50
  120.             while quantia >= 20:
  121.                 ced_20 += 1
  122.                 quantia -= 20
  123.             while quantia >= 10:
  124.                 ced_10 += 1
  125.                 quantia -= 10
  126.             while quantia >= 5:
  127.                 ced_5 += 1
  128.                 quantia -= 5
  129.         else:
  130.             print("Não foi possível sacar, nos desculpe.\nSaldo insuficiente.")
  131.         cedulas = {'100' : ced_100, '50' : ced_50, '20' : ced_20, '10' : ced_10, '5' : ced_5, '2' : ced_2}
  132.         for chave in cedulas:
  133.             if cedulas[chave] > 0:
  134.                 print("Você tirará %d notas de %s\n" % (cedulas[chave], chave))
  135.  
  136.     def extrato(self):
  137.         """
  138.            PRINTA O EXTRATO DO USUÁRIO, PRO FUTURO, SE PRECISO, PODE RETORNAR O SELF.__din
  139.        """
  140.         print("O usuário: %s tem exatamente %.2f reais" % (self.nome, self.__din))
  141.  
  142.     def consultar_dados(self):
  143.         """
  144.             Informação organizada da seguinte forma, conta, nome, cpf, rg, data_nasc, tel, end
  145.        """
  146.         with open('stats.dat', 'a+') as file:
  147.             file.write('{}|{}/{},{}.{}*{}-{}+{}&{}\n' \
  148.                 .format(self.__conta, self.__senha, self.nome, self.__cpf, self.__rg, self.__data_nasc, self.__tel, self.__end, self.__din))
  149.         return(self.nome, self.__conta, 1)
  150.  
  151. def verificar(conta_u, senha_u):
  152.     """
  153.        VERIFICAÇÃO DE TODA CONTA DE USUÁRIO PASSARÁ POR AQUI
  154.    """
  155.     with open('stats.dat', 'r') as file:
  156.             lines = file.readlines()
  157.             for line in lines:
  158.                 eta = line.find('|')
  159.                 conta = line[:eta:]
  160.                 senha = line[eta+1:line.find('/'):]
  161.                 if conta_u == conta and senha_u == senha:
  162.                     nome = line[line.find('/')+1:line.find(','):]
  163.                     cpf = line[line.find(',')+1:line.find('.'):]
  164.                     rg = line[line.find('.')+1:line.find('*'):]
  165.                     data_nascimento = line[line.find('*')+1:line.find('-'):]
  166.                     tel = line[line.find('-')+1:line.find('+'):]
  167.                     end = line[line.find('+')+1:line.find('&'):]
  168.                     din = line[line.find('&')+1::]
  169.                     cliente = Cliente(nome, cpf, rg, data_nascimento, tel, end, din)
  170.                     cliente.acessar_banco()
  171.                     return(True)
  172.                 else:
  173.                     return(False)
  174.  
  175. def main():
  176.     """
  177.        FUNÇÃO PRINCIPAL QUE TODO USUÁRIO SERÁ REDIRECIONADO
  178.    """
  179.     clear()
  180.     if len(sys.argv) < 2:
  181.         conta_u = input("Conta: ")
  182.         senha_u = input("Senha: ")
  183.         print()
  184.         ver = verificar(conta_u, senha_u)
  185.         if ver:
  186.             print("Acessou com sucesso")
  187.         else:
  188.             print("Dados incorretos")
  189.     else:
  190.         # Bloco de instrução para criar conta :D
  191.         if sys.argv[1] == '-c':
  192.             print("Entrando no menu para criar conta", end='')
  193.             for i in range(20):
  194.                 sys.stdout.write('.')
  195.                 sys.stdout.flush()
  196.                 time.sleep(.009)
  197.             print()
  198.             nome = input("Nome: ").title()
  199.             if len(nome) < 1:
  200.                 main()
  201.             cpf = input("CPF: ")
  202.             if len(cpf) < 1:
  203.                 main()
  204.             rg = input("RG: ")
  205.             if len(rg) < 1:
  206.                 main()
  207.             data_nascimento = input("Data de nascimento: ")
  208.             if len(data_nascimento) < 1:
  209.                 main()
  210.             telefone = input("Telefone: ")
  211.             if len(telefone) < 1:
  212.                 main()
  213.             endereco = input("Endereço: ")
  214.             if len(endereco) < 1:
  215.                 main()
  216.             cliente = Cliente(nome, cpf, rg, data_nascimento, telefone, endereco)
  217.             while 1:
  218.                 cliente.acessar_banco()
  219.         elif sys.argv[1] == '-h' or sys.argv[1] == '-help':
  220.             print("Se o argumento sucedendo o py banco.py for -c, irá abrir um menu para criar uma conta.\nSenão \
  221. ele irá diretamente ao menu principal, pedindo informações como conta e senha para você entrar no sistema.\n")
  222.             return('help')
  223.         else:
  224.             print("%s inválido e/ou inesperado. Desculpe-nos.\n" % (sys.argv[1].title()))
  225.  
  226. if __name__ == '__main__':
  227.     try:
  228.         main()
  229.     except KeyboardInterrupt:
  230.         clear()
  231.         print('Exiting', end='')
  232.         for i in range(27):
  233.             sys.stdout.write('.')
  234.             sys.stdout.flush()
  235.             time.sleep(.010)
  236.         else:
  237.             sys.exit(0)
Add Comment
Please, Sign In to add comment