-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClienteRepository.cs
More file actions
85 lines (69 loc) · 2.41 KB
/
Copy pathClienteRepository.cs
File metadata and controls
85 lines (69 loc) · 2.41 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
using System.Globalization;
namespace StudioClientManager;
public class ClienteRepository
{
private readonly List<Cliente> _clientes = new();
private int _proximoId = 1;
public IReadOnlyList<Cliente> Listar() => _clientes;
public Cliente Adicionar(Cliente c)
{
c.Id = _proximoId++;
_clientes.Add(c);
return c;
}
public Cliente? BuscarPorId(int id) => _clientes.FirstOrDefault(x => x.Id == id);
public List<Cliente> BuscarPorNome(string termo)
=> _clientes
.Where(x => x.Nome.Contains(termo, StringComparison.OrdinalIgnoreCase))
.ToList();
public bool Remover(int id)
{
var c = BuscarPorId(id);
if (c == null) return false;
return _clientes.Remove(c);
}
public bool Atualizar(int id, Action<Cliente> update)
{
var c = BuscarPorId(id);
if (c == null) return false;
update(c);
return true;
}
public void SalvarCsv(string caminho)
{
using var sw = new StreamWriter(caminho);
sw.WriteLine("Id;Nome;Telefone;Email;Estilo;ValorHora;Observacoes");
foreach (var c in _clientes)
{
// decimal com ponto pra ficar estável em qualquer Windows/locale
var valor = c.ValorHora.ToString(CultureInfo.InvariantCulture);
sw.WriteLine($"{c.Id};{Esc(c.Nome)};{Esc(c.Telefone)};{Esc(c.Email)};{Esc(c.Estilo)};{valor};{Esc(c.Observacoes)}");
}
}
public void CarregarCsv(string caminho)
{
if (!File.Exists(caminho)) return;
_clientes.Clear();
_proximoId = 1;
var linhas = File.ReadAllLines(caminho);
foreach (var linha in linhas.Skip(1))
{
if (string.IsNullOrWhiteSpace(linha)) continue;
var p = linha.Split(';');
var c = new Cliente
{
Id = int.Parse(p[0]),
Nome = Des(p[1]),
Telefone = Des(p[2]),
Email = Des(p[3]),
Estilo = Des(p[4]),
ValorHora = decimal.Parse(p[5], CultureInfo.InvariantCulture),
Observacoes = Des(p[6]),
};
_clientes.Add(c);
_proximoId = Math.Max(_proximoId, c.Id + 1);
}
}
private static string Esc(string s) => s.Replace("\n", " ").Replace("\r", " ").Replace(";", ",").Trim();
private static string Des(string s) => s.Trim();
}