-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
604 lines (562 loc) · 27.1 KB
/
Copy pathmain.js
File metadata and controls
604 lines (562 loc) · 27.1 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
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
// ============================================================
// main.js — Interface interativa de terminal | Loja de Roupas
// ============================================================
const readline = require('readline/promises');
const pool = require('./db');
const GerenciadorLojaRoupas = require('./gerenciador');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const g = new GerenciadorLojaRoupas();
// ── Helpers visuais ──────────────────────────────────────────
const SEP = '═'.repeat(52);
const SEP2 = '─'.repeat(52);
function cabecalho(titulo) {
console.log(`\n${SEP}`);
console.log(` ${titulo}`);
console.log(SEP);
}
function linha() { console.log(SEP2); }
function ok(msg) { console.log(`\n ✅ ${msg}`); }
function erro(msg){ console.log(`\n ❌ ${msg}`); }
function info(msg){ console.log(` ℹ️ ${msg}`); }
async function perguntar(prompt) {
return (await rl.question(` ${prompt}`)).trim();
}
async function sim(prompt) {
return (await perguntar(`${prompt} (s/n): `)).toLowerCase() === 's';
}
// ── Helper: exibir info de desconto ──────────────────────────
function descontoLabel(c) {
const motivos = [];
if (c.torceFlamengo == 1 || c.torceFlamengo === true) motivos.push('Flamengo');
if (c.assisteOnePiece == 1 || c.assisteOnePiece === true) motivos.push('One Piece');
if (c.ehDeSousa == 1 || c.ehDeSousa === true) motivos.push('Sousa');
return motivos.length ? `Sim (${motivos.join(', ')})` : 'Não';
}
// ── Menus ────────────────────────────────────────────────────
async function menuPrincipal() {
cabecalho('LOJA DE ROUPAS — SISTEMA CRUD');
console.log(' 1. Gestão de Clientes');
console.log(' 2. Gestão de Vendedores');
console.log(' 3. Gestão de Categorias');
console.log(' 4. Gestão de Produtos');
console.log(' 5. Realizar Venda (PDV)');
console.log(' 6. Listar Vendas');
console.log(' 7. Detalhes de uma Venda');
console.log(' 8. Relatórios');
console.log(' 0. Sair');
linha();
return perguntar('Escolha: ');
}
// ── Módulo: Clientes ─────────────────────────────────────────
async function menuClientes() {
cabecalho('CLIENTES');
console.log(' 1. Listar todos');
console.log(' 2. Inserir');
console.log(' 3. Pesquisar por nome');
console.log(' 4. Exibir um (por ID)');
console.log(' 5. Alterar');
console.log(' 6. Remover');
console.log(' 7. Ver compras do cliente');
console.log(' 0. Voltar');
linha();
const sub = await perguntar('Opção: ');
switch (sub) {
case '1': {
const lista = await g.listarClientes();
if (!lista.length) { info('Nenhum cliente cadastrado.'); break; }
console.table(lista.map(c => ({
ID: c.id, Nome: c.nome, CPF: c.cpf,
Email: c.email, Telefone: c.telefone,
Desconto: descontoLabel(c)
})));
break;
}
case '2': {
const nome = await perguntar('Nome: ');
const cpf = await perguntar('CPF (xxx.xxx.xxx-xx): ');
const email = await perguntar('E-mail: ');
const telefone = await perguntar('Telefone: ');
console.log('\n 📋 Critérios de desconto (10%):');
const flamengo = await sim('Torce pro Flamengo?');
const onePiece = await sim('Assiste One Piece?');
const sousa = await sim('É de Sousa?');
const c = await g.inserirCliente(nome, cpf, email, telefone, flamengo, onePiece, sousa);
ok(`Cliente inserido com ID: ${c.id}`);
if (flamengo || onePiece || sousa) {
info('Cliente tem direito a 10% de desconto nas compras!');
}
break;
}
case '3': {
const nome = await perguntar('Nome (parcial): ');
const res = await g.procurarClientePorNome(nome);
if (!res.length) { info('Nenhum cliente encontrado.'); break; }
console.table(res.map(c => ({ ID: c.id, Nome: c.nome, CPF: c.cpf, Email: c.email, Desconto: descontoLabel(c) })));
break;
}
case '4': {
const id = await perguntar('ID do cliente: ');
const c = await g.exibirCliente(id);
if (!c) { erro('Cliente não encontrado.'); break; }
console.table([{
ID: c.id, Nome: c.nome, CPF: c.cpf,
Email: c.email, Telefone: c.telefone,
Desconto: descontoLabel(c),
'Cadastrado em': c.criadoEm
}]);
break;
}
case '5': {
const id = await perguntar('ID do cliente para alterar: ');
const atual = await g.exibirCliente(id);
if (!atual) { erro('Cliente não encontrado.'); break; }
info(`Editando: ${atual.nome} | Deixe em branco para manter o valor atual.`);
const nome = (await perguntar(`Nome [${atual.nome}]: `)) || atual.nome;
const cpf = (await perguntar(`CPF [${atual.cpf}]: `)) || atual.cpf;
const email = (await perguntar(`Email [${atual.email}]: `)) || atual.email;
const telefone = (await perguntar(`Telefone [${atual.telefone}]: `)) || atual.telefone;
console.log('\n 📋 Critérios de desconto:');
const flamengo = await sim(`Torce pro Flamengo? (atual: ${atual.torceFlamengo == 1 || atual.torceFlamengo === true ? 's' : 'n'})`);
const onePiece = await sim(`Assiste One Piece? (atual: ${atual.assisteOnePiece == 1 || atual.assisteOnePiece === true ? 's' : 'n'})`);
const sousa = await sim(`É de Sousa? (atual: ${atual.ehDeSousa == 1 || atual.ehDeSousa === true ? 's' : 'n'})`);
await g.alterarCliente(id, nome, cpf, email, telefone, flamengo, onePiece, sousa);
ok('Cliente alterado com sucesso!');
break;
}
case '6': {
const id = await perguntar('ID do cliente para remover: ');
const confirma = await sim(`Confirma remoção do cliente ID ${id}?`);
if (!confirma) { info('Operação cancelada.'); break; }
await g.removerCliente(id);
ok('Cliente removido com sucesso!');
break;
}
case '7': {
const id = await perguntar('ID do cliente: ');
const res = await g.exibirComprasDoCliente(id);
if (!res.length) { info('Nenhuma compra encontrada.'); break; }
console.table(res.map(v => ({
'Venda ID': v.id,
Data: new Date(v.data_venda).toLocaleDateString('pt-BR'),
'Total Líq.': `R$ ${parseFloat(v.total_liquido).toFixed(2)}`,
Desconto: `${v.desconto_percent}%`,
Status: v.status,
Vendedor: v.nome_vendedor
})));
break;
}
}
}
// ── Módulo: Vendedores ────────────────────────────────────────
async function menuVendedores() {
cabecalho('VENDEDORES');
console.log(' 1. Listar todos');
console.log(' 2. Inserir');
console.log(' 3. Pesquisar por nome');
console.log(' 4. Exibir um (por ID)');
console.log(' 5. Alterar');
console.log(' 6. Remover');
console.log(' 0. Voltar');
linha();
const sub = await perguntar('Opção: ');
switch (sub) {
case '1': {
const lista = await g.listarVendedores();
if (!lista.length) { info('Nenhum vendedor cadastrado.'); break; }
console.table(lista.map(v => ({
ID: v.id, Nome: v.nome, CPF: v.cpf,
Matrícula: v.matricula, Ativo: v.ativo == 1 || v.ativo === true ? 'Sim' : 'Não'
})));
break;
}
case '2': {
const nome = await perguntar('Nome: ');
const cpf = await perguntar('CPF (xxx.xxx.xxx-xx): ');
const matricula = await perguntar('Matrícula: ');
const v = await g.inserirVendedor(nome, cpf, matricula);
ok(`Vendedor inserido com ID: ${v.id}`);
break;
}
case '3': {
const nome = await perguntar('Nome (parcial): ');
const res = await g.procurarVendedorPorNome(nome);
if (!res.length) { info('Nenhum vendedor encontrado.'); break; }
console.table(res.map(v => ({ ID: v.id, Nome: v.nome, Matrícula: v.matricula, Ativo: v.ativo == 1 || v.ativo === true ? 'Sim' : 'Não' })));
break;
}
case '4': {
const id = await perguntar('ID do vendedor: ');
const v = await g.exibirVendedor(id);
if (!v) { erro('Vendedor não encontrado.'); break; }
console.table([{ ID: v.id, Nome: v.nome, CPF: v.cpf, Matrícula: v.matricula, Ativo: v.ativo == 1 || v.ativo === true ? 'Sim' : 'Não' }]);
break;
}
case '5': {
const id = await perguntar('ID do vendedor para alterar: ');
const atual = await g.exibirVendedor(id);
if (!atual) { erro('Vendedor não encontrado.'); break; }
const nome = (await perguntar(`Nome [${atual.nome}]: `)) || atual.nome;
const cpf = (await perguntar(`CPF [${atual.cpf}]: `)) || atual.cpf;
const matricula = (await perguntar(`Matrícula [${atual.matricula}]: `)) || atual.matricula;
const ativo = await sim(`Ativo? (atual: ${atual.ativo == 1 || atual.ativo === true ? 's' : 'n'})`);
await g.alterarVendedor(id, nome, cpf, matricula, ativo);
ok('Vendedor alterado com sucesso!');
break;
}
case '6': {
const id = await perguntar('ID do vendedor para remover: ');
const confirma = await sim(`Confirma remoção do vendedor ID ${id}?`);
if (!confirma) { info('Operação cancelada.'); break; }
await g.removerVendedor(id);
ok('Vendedor removido com sucesso!');
break;
}
}
}
// ── Módulo: Categorias ────────────────────────────────────────
async function menuCategorias() {
cabecalho('CATEGORIAS');
console.log(' 1. Listar todas');
console.log(' 2. Inserir');
console.log(' 3. Pesquisar por nome');
console.log(' 4. Exibir uma (por ID)');
console.log(' 5. Alterar');
console.log(' 6. Remover');
console.log(' 0. Voltar');
linha();
const sub = await perguntar('Opção: ');
switch (sub) {
case '1': {
const lista = await g.listarCategorias();
if (!lista.length) { info('Nenhuma categoria cadastrada.'); break; }
console.table(lista.map(c => ({ ID: c.id, Nome: c.nome })));
break;
}
case '2': {
const nome = await perguntar('Nome da categoria: ');
const c = await g.inserirCategoria(nome);
ok(`Categoria inserida com ID: ${c.id}`);
break;
}
case '3': {
const nome = await perguntar('Nome (parcial): ');
const res = await g.procurarCategoriaPorNome(nome);
if (!res.length) { info('Nenhuma categoria encontrada.'); break; }
console.table(res.map(c => ({ ID: c.id, Nome: c.nome })));
break;
}
case '4': {
const id = await perguntar('ID da categoria: ');
const c = await g.exibirCategoria(id);
if (!c) { erro('Categoria não encontrada.'); break; }
console.table([{ ID: c.id, Nome: c.nome }]);
break;
}
case '5': {
const id = await perguntar('ID da categoria para alterar: ');
const nome = await perguntar('Novo nome: ');
await g.alterarCategoria(id, nome);
ok('Categoria alterada com sucesso!');
break;
}
case '6': {
const id = await perguntar('ID da categoria para remover: ');
const confirma = await sim(`Confirma remoção da categoria ID ${id}?`);
if (!confirma) { info('Operação cancelada.'); break; }
await g.removerCategoria(id);
ok('Categoria removida com sucesso!');
break;
}
}
}
// ── Módulo: Produtos ─────────────────────────────────────────
function tabelaProdutos(lista) {
console.table(lista.map(p => ({
ID: p.id, Nome: p.nome, Categoria: p.categoriaNome,
Marca: p.marca, Tamanho: p.tamanho,
'Preço': `R$ ${p.preco.toFixed(2)}`, Estoque: p.quantidadeEstoque,
'Mari': p.fabricadoEmMari == 1 || p.fabricadoEmMari === true ? 'Sim' : 'Não'
})));
}
async function menuProdutos() {
cabecalho('PRODUTOS');
console.log(' 1. Listar todos');
console.log(' 2. Inserir');
console.log(' 3. Pesquisar por nome');
console.log(' 4. Exibir um (por ID)');
console.log(' 5. Alterar');
console.log(' 6. Remover');
console.log(' 7. Buscar por faixa de preço');
console.log(' 8. Buscar por categoria');
console.log(' 9. Fabricados em Mari');
console.log(' 10. Estoque baixo (< 5 un.)');
console.log(' 0. Voltar');
linha();
const sub = await perguntar('Opção: ');
switch (sub) {
case '1': {
const lista = await g.listarProdutos();
if (!lista.length) { info('Nenhum produto cadastrado.'); break; }
tabelaProdutos(lista);
break;
}
case '2': {
const cats = await g.listarCategorias();
if (!cats.length) { erro('Cadastre ao menos uma categoria antes de inserir produtos.'); break; }
console.log('\n Categorias disponíveis:');
cats.forEach(c => console.log(` [${c.id}] ${c.nome}`));
const catId = await perguntar('ID da Categoria: ');
const nome = await perguntar('Nome do produto: ');
const marca = await perguntar('Marca: ');
const preco = await perguntar('Preço (ex: 59.90): ');
const qtd = await perguntar('Quantidade em estoque: ');
const tamanho = await perguntar('Tamanho (PP/P/M/G/GG ou número, ex: 40): ');
const mari = await sim('Fabricado em Mari?');
const p = await g.inserirProduto(catId, nome, marca, preco, qtd, tamanho, mari);
ok(`Produto inserido com ID: ${p.id}`);
break;
}
case '3': {
const nome = await perguntar('Nome (parcial): ');
const res = await g.procurarProdutoPorNome(nome);
if (!res.length) { info('Nenhum produto encontrado.'); break; }
tabelaProdutos(res);
break;
}
case '4': {
const id = await perguntar('ID do produto: ');
const p = await g.exibirProduto(id);
if (!p) { erro('Produto não encontrado.'); break; }
console.table([{
ID: p.id, Nome: p.nome, Categoria: p.categoriaNome, Marca: p.marca,
Tamanho: p.tamanho, 'Preço': `R$ ${p.preco.toFixed(2)}`,
Estoque: p.quantidadeEstoque, 'Val.Estoque': `R$ ${p.valorEstoque().toFixed(2)}`,
'Mari': p.fabricadoEmMari == 1 || p.fabricadoEmMari === true ? 'Sim' : 'Não'
}]);
break;
}
case '5': {
const id = await perguntar('ID do produto para alterar: ');
const atual = await g.exibirProduto(id);
if (!atual) { erro('Produto não encontrado.'); break; }
info(`Editando: ${atual.nome} | Deixe em branco para manter o valor atual.`);
const cats = await g.listarCategorias();
cats.forEach(c => console.log(` [${c.id}] ${c.nome}`));
const catId = (await perguntar(`ID Categoria [${atual.categoriaId}]: `)) || atual.categoriaId;
const nome = (await perguntar(`Nome [${atual.nome}]: `)) || atual.nome;
const marca = (await perguntar(`Marca [${atual.marca}]: `)) || atual.marca;
const preco = (await perguntar(`Preço [${atual.preco}]: `)) || atual.preco;
const qtd = (await perguntar(`Estoque [${atual.quantidadeEstoque}]: `))|| atual.quantidadeEstoque;
const tamanho = (await perguntar(`Tamanho [${atual.tamanho}]: `)) || atual.tamanho;
const mari = await sim(`Fabricado em Mari? (atual: ${atual.fabricadoEmMari == 1 || atual.fabricadoEmMari === true ? 's' : 'n'})`);
await g.alterarProduto(id, catId, nome, marca, preco, qtd, tamanho, mari);
ok('Produto alterado com sucesso!');
break;
}
case '6': {
const id = await perguntar('ID do produto para remover: ');
const confirma = await sim(`Confirma remoção do produto ID ${id}?`);
if (!confirma) { info('Operação cancelada.'); break; }
await g.removerProduto(id);
ok('Produto removido com sucesso!');
break;
}
case '7': {
const min = await perguntar('Preço mínimo (ex: 10.00): ');
const max = await perguntar('Preço máximo (ex: 100.00): ');
const res = await g.procurarProdutoPorFaixaDePreco(parseFloat(min), parseFloat(max));
if (!res.length) { info('Nenhum produto nessa faixa de preço.'); break; }
tabelaProdutos(res);
break;
}
case '8': {
const cats = await g.listarCategorias();
if (!cats.length) { info('Nenhuma categoria cadastrada.'); break; }
console.log('\n Categorias disponíveis:');
cats.forEach(c => console.log(` [${c.id}] ${c.nome}`));
const catId = await perguntar('ID da Categoria: ');
const res = await g.procurarProdutoPorCategoria(catId);
if (!res.length) { info('Nenhum produto nessa categoria.'); break; }
tabelaProdutos(res);
break;
}
case '9': {
const res = await g.listarProdutosFabricadosEmMari();
if (!res.length) { info('Nenhum produto fabricado em Mari.'); break; }
tabelaProdutos(res);
break;
}
case '10': {
const limite = await perguntar('Limite mínimo de estoque (padrão 5): ');
const res = await g.listarEstoqueBaixo(parseInt(limite) || 5);
if (!res.length) { info('Nenhum produto com estoque baixo.'); break; }
tabelaProdutos(res);
break;
}
}
}
// ── Módulo: PDV ───────────────────────────────────────────────
async function menuVenda() {
cabecalho('REALIZAR VENDA — PDV');
const clienteId = await perguntar('ID do Cliente: ');
const vendedorId = await perguntar('ID do Vendedor: ');
const itens = [];
let continuar = true;
while (continuar) {
console.log('\n Produtos disponíveis:');
const prods = await g.listarProdutos();
prods.forEach(p => console.log(` [${p.id}] ${p.nome} | ${p.marca} | Tam: ${p.tamanho} | R$ ${p.preco.toFixed(2)} | Estoque: ${p.quantidadeEstoque}`));
linha();
const prodId = await perguntar('ID do Produto: ');
const qtd = await perguntar('Quantidade: ');
itens.push({ produtoId: parseInt(prodId), qtd: parseInt(qtd) });
continuar = await sim('Adicionar mais um produto?');
}
console.log('\n Formas de pagamento: CARTAO | BOLETO | PIX | DINHEIRO | BERRIES');
const pagamento = (await perguntar('Forma de pagamento: ')).toUpperCase();
const resultado = await g.realizarVenda(clienteId, vendedorId, itens, pagamento);
linha();
console.log(`\n 💰 VENDA CONCLUÍDA!`);
console.log(` Cliente : ${resultado.nomeCliente}`);
console.log(` Venda ID : ${resultado.venda.id}`);
console.log(` Total Bruto: R$ ${resultado.venda.totalBruto.toFixed(2)}`);
if (resultado.descontoPercent > 0) {
console.log(` Desconto : ${resultado.descontoPercent}% (Flamengo / One Piece / Sousa)`);
console.log(` Economia : R$ ${resultado.venda.economiaNaCompra().toFixed(2)}`);
}
console.log(` Total Líq. : R$ ${resultado.venda.totalLiquido.toFixed(2)}`);
console.log(` Pagamento : ${resultado.pagamento.tipo} — ${resultado.pagamento.statusConfirmacao}`);
console.log(` Itens : ${resultado.itens.length}`);
linha();
}
// ── Módulo: Relatórios ────────────────────────────────────────
async function menuRelatorios() {
cabecalho('RELATÓRIOS');
console.log(' 1. Relatório Geral (resumo)');
console.log(' 2. Relatório de Vendas por Vendedor');
console.log(' 3. Produtos mais vendidos');
console.log(' 0. Voltar');
linha();
const sub = await perguntar('Opção: ');
switch (sub) {
case '1': {
const r = await g.relatorioGeral();
cabecalho('RELATÓRIO GERAL — LOJA DE ROUPAS');
console.log(` Categorias : ${r.qtd_categorias}`);
console.log(` Produtos : ${r.qtd_produtos}`);
console.log(` Clientes : ${r.qtd_clientes}`);
console.log(` Vendedores ativos: ${r.qtd_vendedores_ativos}`);
linha();
console.log(` Vendas concluídas: ${r.qtd_vendas}`);
console.log(` Faturamento total: R$ ${parseFloat(r.faturamento_total).toFixed(2)}`);
console.log(` Ticket médio : R$ ${parseFloat(r.ticket_medio).toFixed(2)}`);
console.log(` Val. total estoque: R$ ${parseFloat(r.valor_total_estoque).toFixed(2)}`);
linha();
break;
}
case '2': {
const rows = await g.relatorioVendedores();
if (!rows.length) { info('Nenhum dado disponível.'); break; }
cabecalho('RELATÓRIO POR VENDEDOR');
console.table(rows.map(r => ({
Vendedor : r.vendedor,
Mês : r.mes ? new Date(r.mes).toLocaleDateString('pt-BR', { month: '2-digit', year: 'numeric' }) : '-',
'Nº Vendas' : r.total_vendas,
'Faturamento': `R$ ${parseFloat(r.faturamento).toFixed(2)}`,
'Ticket Médio': `R$ ${parseFloat(r.ticket_medio).toFixed(2)}`
})));
break;
}
case '3': {
const rows = await g.relatorioProdutosMaisVendidos();
if (!rows.length) { info('Nenhum dado disponível.'); break; }
cabecalho('PRODUTOS MAIS VENDIDOS (TOP 10)');
console.table(rows.map(r => ({
Produto : r.nome,
Marca : r.marca,
'Qtd. Vendida' : r.total_vendido,
'Receita Gerada': `R$ ${parseFloat(r.receita).toFixed(2)}`
})));
break;
}
}
}
// ── Loop principal ────────────────────────────────────────────
async function main() {
console.clear();
console.log('\n Conectando ao banco de dados...');
try {
await pool.execute('SELECT 1');
ok('Conexão estabelecida!\n');
} catch (e) {
erro(`Não foi possível conectar ao banco: ${e.message}`);
erro('Verifique o arquivo .env e tente novamente.');
process.exit(1);
}
let executar = true;
while (executar) {
try {
const opt = await menuPrincipal();
switch (opt) {
case '1': await menuClientes(); break;
case '2': await menuVendedores(); break;
case '3': await menuCategorias(); break;
case '4': await menuProdutos(); break;
case '5': await menuVenda(); break;
case '6': {
cabecalho('VENDAS REALIZADAS');
const vendas = await g.listarVendas();
if (!vendas.length) { info('Nenhuma venda registrada.'); break; }
console.table(vendas.map(v => ({
ID : v.id,
Data : new Date(v.data_venda).toLocaleDateString('pt-BR'),
Cliente : v.nome_cliente,
Vendedor: v.nome_vendedor,
'Total' : `R$ ${parseFloat(v.total_liquido).toFixed(2)}`,
Desconto: `${v.desconto_percent}%`,
Status : v.status,
Pagamento: v.forma_pagamento || '-'
})));
break;
}
case '7': {
const id = await perguntar('ID da venda: ');
const res = await g.exibirVenda(id);
if (!res) { erro('Venda não encontrada.'); break; }
cabecalho(`VENDA #${res.venda.id}`);
console.log(` Cliente : ${res.venda.nome_cliente}`);
console.log(` Vendedor : ${res.venda.nome_vendedor}`);
console.log(` Data : ${new Date(res.venda.data_venda).toLocaleString('pt-BR')}`);
console.log(` Desconto : ${res.venda.desconto_percent}%`);
console.log(` Bruto : R$ ${parseFloat(res.venda.total_bruto).toFixed(2)}`);
console.log(` Líquido : R$ ${parseFloat(res.venda.total_liquido).toFixed(2)}`);
console.log(` Status : ${res.venda.status}`);
if (res.pagamento) {
console.log(` Pagamento: ${res.pagamento.tipo} — ${res.pagamento.status_confirmacao}`);
}
linha();
console.log(' Itens:');
console.table(res.itens.map(i => ({
Produto : i.nome_produto, Marca: i.marca, Tamanho: i.tamanho,
Qtd : i.quantidade,
'Preço Unit.': `R$ ${parseFloat(i.preco_unitario).toFixed(2)}`,
Subtotal : `R$ ${(i.quantidade * parseFloat(i.preco_unitario)).toFixed(2)}`
})));
break;
}
case '8': await menuRelatorios(); break;
case '0':
executar = false;
cabecalho('Encerrando sistema... Até logo! 👔');
break;
default:
erro('Opção inválida. Tente novamente.');
}
} catch (err) {
erro(`Erro: ${err.message}`);
}
}
await pool.end();
rl.close();
}
main();