Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
158 lines (132 loc) · 5.15 KB
/
Copy pathmain.py
File metadata and controls
158 lines (132 loc) · 5.15 KB
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
import os
import datetime
import json
def limpar_tela():
sistema = os.name
if sistema == "posix":
os.system("clear")
elif sistema == "nt":
os.system("cls")
def salvar_agenda(agenda, filename="agenda_data.json"):
with open(filename, "w") as file:
json.dump(agenda, file)
def carregar_agenda(filename="agenda_data.json"):
try:
with open(filename, "r") as file:
return json.load(file)
except FileNotFoundError:
return {}
def incluir_contato(agenda, nome, telefone):
if nome in agenda:
return "Contato já existe na agenda."
agenda[nome] = {
"telefone": telefone,
"data_inclusao": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
salvar_agenda(agenda)
return f"Contato {nome} adicionado com sucesso!"
def pesquisar_contato(agenda, nome):
contato = agenda.get(nome)
if contato:
return contato["telefone"]
return "Contato não encontrado."
def atualizar_contato(agenda, nome):
if nome not in agenda:
return "Contato não encontrado."
print("\nO que você gostaria de atualizar?")
print("1. Nome")
print("2. Telefone")
print("3. Nome e Telefone")
escolha = input("Escolha uma opção (1-3): ")
if escolha == "1":
novo_nome = input("Digite o novo nome: ")
agenda[novo_nome] = agenda.pop(nome)
salvar_agenda(agenda)
return f"Nome de '{nome}' atualizado para '{novo_nome}' com sucesso!"
elif escolha == "2":
novo_telefone = input("Digite o novo telefone: ")
if not novo_telefone.isdigit() or len(novo_telefone) not in [10, 11]:
return "Número de telefone inválido. Certifique-se de que ele contém apenas dígitos e tem 10 ou 11 números."
agenda[nome]["telefone"] = novo_telefone
salvar_agenda(agenda)
return f"Telefone de {nome} atualizado com sucesso!"
elif escolha == "3":
novo_nome = input("Digite o novo nome: ")
novo_telefone = input("Digite o novo telefone: ")
if not novo_telefone.isdigit() or len(novo_telefone) not in [10, 11]:
return "Número de telefone inválido. Certifique-se de que ele contém apenas dígitos e tem 10 ou 11 números."
agenda[novo_nome] = {
"telefone": novo_telefone,
"data_inclusao": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
del agenda[nome]
salvar_agenda(agenda)
return f"Nome e telefone de '{nome}' atualizados com sucesso!"
else:
return "Opção inválida."
def excluir_contato(agenda, nome):
if nome not in agenda:
return "Contato não encontrado."
del agenda[nome]
salvar_agenda(agenda)
return f"Contato {nome} excluído com sucesso!"
def ordenar_contatos(agenda, por="nome"):
if por == "nome":
return sorted(agenda.items(), key=lambda x: x[0])
elif por == "data":
return sorted(agenda.items(), key=lambda x: x[1]["data_inclusao"], reverse=True)
else:
return []
def registrar_log(mensagem):
with open("agenda_logs.txt", "a") as log_file:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_file.write(f"{timestamp} - {mensagem}\n")
def interface_usuario():
agenda = carregar_agenda()
while True:
limpar_tela()
print("\n" + "=" * 40)
print("Agenda de Contatos".center(40))
print("=" * 40)
print("1. Incluir Contato")
print("2. Pesquisar Contato")
print("3. Atualizar Contato")
print("4. Excluir Contato")
print("5. Mostrar Contatos Ordenados por Nome")
print("6. Mostrar Contatos Ordenados por Data de Inclusão")
print("7. Sair")
opcao = input("Escolha uma opção (1-7): ")
if opcao == "1":
nome = input("Nome do Contato: ")
telefone = input("Telefone do Contato: ")
mensagem = incluir_contato(agenda, nome, telefone)
print(mensagem)
registrar_log(mensagem)
elif opcao == "2":
nome = input("Nome do Contato: ")
print(f"Telefone: {pesquisar_contato(agenda, nome)}")
elif opcao == "3":
nome = input("Nome do Contato a ser Atualizado: ")
mensagem = atualizar_contato(agenda, nome)
print(mensagem)
registrar_log(mensagem)
elif opcao == "4":
nome = input("Nome do Contato a ser Excluído: ")
mensagem = excluir_contato(agenda, nome)
print(mensagem)
registrar_log(mensagem)
elif opcao in ["5", "6"]:
criterio = "nome" if opcao == "5" else "data"
contatos_ordenados = ordenar_contatos(agenda, por=criterio)
for nome, dados in contatos_ordenados:
print(
f"{nome}: {dados['telefone']} (Adicionado em: {dados['data_inclusao']})"
)
elif opcao == "7":
print("Obrigado por usar a Agenda de Contatos!")
break
else:
print("Opção inválida. Tente novamente.")
input("\nPressione ENTER para continuar...")
if __name__ == "__main__":
interface_usuario()