-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.cjs
More file actions
2200 lines (1859 loc) · 64.4 KB
/
Copy pathserver.cjs
File metadata and controls
2200 lines (1859 loc) · 64.4 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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require('dotenv').config();
const express = require('express');
const path = require('path');
const { createClient } = require('@supabase/supabase-js');
const cors = require('cors');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const { create } = require('@wppconnect-team/wppconnect');
const cookieParser = require('cookie-parser');
const ExcelJS = require('exceljs');
const multer = require('multer');
const fs = require('fs');
const mongoose = require('mongoose');
let whatsappClient = null;
const SESSION_DIR = path.join(__dirname, 'tokens');
const SESSION_FILE = path.join(SESSION_DIR, 'salon-bot.json');
const app = express();
const port = process.env.PORT || 3000;
// Configuração do Supabase
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);
app.use(cookieParser());
// Criar diretório se não existir
if (!fs.existsSync(SESSION_DIR)) {
fs.mkdirSync(SESSION_DIR, { recursive: true });
}
const corsOptions = {
origin: '*', // Permite qualquer origem
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Permite os métodos HTTP que você precisa
allowedHeaders: ['Content-Type'], // Permite esses cabeçalhos específicos
credentials: true, // Permite cookies (importante se for necessário)
};
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB conectado com sucesso'))
.catch(err => console.error('Erro ao conectar ao MongoDB:', err));
// Modelo para galeria
const galeriaSchema = new mongoose.Schema({
titulo: { type: String, required: true },
imagem: { type: String, required: true }, // Caminho da imagem no servidor
criadoEm: { type: Date, default: Date.now }
});
const Galeria = mongoose.model('Galeria', galeriaSchema);
// Configuração do Multer para upload de imagens
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadPath = path.join(__dirname, 'public/uploads');
if (!fs.existsSync(uploadPath)) {
fs.mkdirSync(uploadPath, { recursive: true });
}
cb(null, uploadPath);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Apenas imagens são permitidas!'), false);
}
},
limits: {
fileSize: 5 * 1024 * 1024 // 5MB
}
});
// Middlewares
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
const checkAuth = (req, res, next) => {
const userData = req.cookies.userData; // Obtendo os dados do usuário do cookie
if (!userData) {
return res.status(403).send('Acesso negado'); // Caso não tenha cookie
}
const parsedUser = JSON.parse(userData);
// Verificando se o tipo do usuário é 'admin'
if (parsedUser.tipo === 'admin') {
next(); // Usuário autorizado, segue para a rota do admin
} else {
return res.status(403).send('Acesso negado');
}
};
// Rotas para servir os arquivos HTML
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html')));
app.get('/home', (req, res) => res.sendFile(path.join(__dirname, 'public', 'home.html')));
app.get('/login', (req, res) => res.sendFile(path.join(__dirname, 'public', 'login.html')));
app.get('/galeria', (req, res) => res.sendFile(path.join(__dirname, 'public', 'galeria.html')));
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));
// app.get('/admin', (req, res) => res.sendFile(path.join(__dirname, 'public', 'admin.html')));
app.get('/admin', checkAuth, async (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});
// Rota para a página inicial logada
app.get('/logado', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'logado.html'), {
headers: {
'Content-Type': 'text/html',
'Cache-Control': 'no-cache'
}
});
});
// Rota para a página de agendamentos
app.get('/logado/agendamentos', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'logado.html'), {
headers: {
'Content-Type': 'text/html',
'Cache-Control': 'no-cache'
}
});
});
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
});
// Rota para enviar email de contato
app.post('/api/contact', async (req, res) => {
const { name, email, phone, message } = req.body;
// Validação básica
if (!name || !email || !message) {
return res.status(400).json({ error: 'Nome, email e mensagem são obrigatórios' });
}
// Configuração do transporter (substitua com suas credenciais SMTP)
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true para 465, false para outras portas
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
});
// Configuração do email
const mailOptions = {
from: `"Formulário de Contato" <${email}>`,
to: 'salaopaulatrancas@gmail.com',
subject: `Nova mensagem de ${name} - Site Paula Tranças`,
text: `
Nome: ${name}
Email: ${email}
Telefone: ${phone || 'Não informado'}
Mensagem:
${message}
`,
html: `
<h2>Nova mensagem do site Paula Tranças</h2>
<p><strong>Nome:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Telefone:</strong> ${phone || 'Não informado'}</p>
<p><strong>Mensagem:</strong></p>
<p>${message.replace(/\n/g, '<br>')}</p>
`
};
try {
await transporter.sendMail(mailOptions);
res.status(200).json({ message: 'Mensagem enviada com sucesso!' });
} catch (error) {
console.error('Erro ao enviar email:', error);
res.status(500).json({ error: 'Ocorreu um erro ao enviar a mensagem. Por favor, tente novamente mais tarde.' });
}
});
// Função para gerar senha
function gerarSenha() {
const letras = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numeros = '0123456789';
let senha = '';
for (let i = 0; i < 4; i++) {
senha += letras.charAt(Math.floor(Math.random() * letras.length));
}
for (let i = 0; i < 3; i++) {
senha += numeros.charAt(Math.floor(Math.random() * numeros.length));
}
return senha;
}
// Busca usuário por email
async function findUserByEmail(email) {
const { data, error } = await supabase
.from('users')
.select('id, email, username')
.eq('email', email)
.single();
if (error) {
console.error('Erro ao buscar usuário por email:', error);
return null;
}
return data;
}
// Atualiza a senha do usuário
async function updateUserPassword(userId, newPassword) {
const { error } = await supabase
.from('users')
.update({ password_plaintext: newPassword })
.eq('id', userId);
if (error) {
throw error;
}
}
// Rota para recuperação de senha
app.post('/api/forgot-password', async (req, res) => {
try {
const { email } = req.body;
// Aqui você deve verificar se o email existe no seu banco de dados
// Esta é uma implementação simulada - substitua pela sua lógica real
const user = await findUserByEmail(email); // Você precisa implementar esta função
if (!user) {
return res.status(404).json({ success: false, error: 'Email não encontrado' });
}
// Gera nova senha
const newPassword = gerarSenha();
// Atualiza a senha no banco de dados (implemente esta função)
await updateUserPassword(user.id, newPassword);
// Envia email com a nova senha
const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: 'Recuperação de Senha - Salão de Beleza',
html: `
<h2>Recuperação de Senha</h2>
<p>Você solicitou uma nova senha para acessar o sistema do Salão de Beleza.</p>
<p>Sua nova senha é: <strong>${newPassword}</strong></p>
<p>Recomendamos que você altere esta senha após o login.</p>
<p>Caso não tenha solicitado esta alteração, por favor ignore este email.</p>
`
};
await transporter.sendMail(mailOptions);
res.json({ success: true });
} catch (error) {
console.error('Erro na recuperação de senha:', error);
res.status(500).json({ success: false, error: 'Erro ao processar solicitação' });
}
});
app.post('/api/send-confirmation-email', async (req, res) => {
try {
const { email, subject, body } = req.body;
const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: subject,
html: body
};
await transporter.sendMail(mailOptions);
res.status(200).json({ message: 'E-mail enviado com sucesso' });
} catch (error) {
console.error('Erro ao enviar e-mail:', error);
res.status(500).json({ error: 'Erro ao enviar e-mail' });
}
});
// Rota para enviar mensagem via WhatsApp
app.post('/api/send-whatsapp-confirmation', async (req, res) => {
try {
const { clientPhone, appointmentDetails } = req.body;
if (!whatsappClient) {
return res.status(500).json({
success: false,
error: "WhatsApp não conectado. Por favor, reinicie o servidor."
});
}
// Validação dos dados
if (!clientPhone || !appointmentDetails) {
return res.status(400).json({
success: false,
error: "Dados incompletos"
});
}
const formattedPhone = `55${clientPhone.replace(/\D/g, '')}@c.us`;
const message = `📅 *Confirmação de Agendamento* \n\n` +
`✅ *Serviço:* ${appointmentDetails.service}\n` +
`👩🏾💼 *Profissional:* ${appointmentDetails.professional}\n` +
`📆 *Data:* ${appointmentDetails.date}\n` +
`⏰ *Horário:* ${appointmentDetails.time}\n\n` +
`_Agradecemos sua preferência!_`;
// Envia a mensagem
await whatsappClient.sendText(formattedPhone, message);
res.json({ success: true });
} catch (error) {
console.error("Erro ao enviar WhatsApp:", error);
res.status(500).json({
success: false,
error: error.message || "Falha no envio"
});
}
});
// Health Check
app.get('/health', (req, res) => {
res.status(whatsappClient ? 200 : 503).json({
status: whatsappClient ? 'healthy' : 'unavailable',
timestamp: new Date()
});
});
async function startWhatsappBot() {
try {
const sessionExists = fs.existsSync(SESSION_FILE);
const client = await create({
session: 'salon-bot',
puppeteerOptions: {
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium',
headless: "new",
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-gpu',
'--disable-dev-shm-usage',
'--single-process',
'--no-zygote'
],
ignoreDefaultArgs: ['--disable-extensions']
},
catchQR: (base64Qr) => {
if (!sessionExists) {
console.log('=== SCANEAE ESTE QR CODE UMA VEZ ===');
console.log('Base64 QR:', base64Qr);
}
},
statusFind: (status) => {
console.log('Status:', status);
if (status === 'authenticated') {
console.log('✅ Login realizado!');
}
}
});
client.on('authenticated', (session) => {
fs.writeFileSync(SESSION_FILE, JSON.stringify(session));
});
client.onMessage(async (message) => {
if (message.body === '!ping') {
await client.sendText(message.from, '🏓 Pong!');
}
});
console.log('🤖 Bot iniciado com sucesso');
} catch (error) {
console.error('Erro crítico no bot:', error);
// Não encerre o processo, permita reinicialização
setTimeout(startWhatsappBot, 30000); // Tenta reiniciar em 30 segundos
}
}
// Rota para obter todos os usuários
app.get('/api/users', async (req, res) => {
try {
const { data, error } = await supabase
.from('users')
.select('*')
.order('created_at', { ascending: false });
if (error) throw error;
res.json(data);
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rota para obter um usuário específico
app.get('/api/users/:id', async (req, res) => {
try {
const { id } = req.params;
const { data, error } = await supabase
.from('users')
.select('*')
.eq('id', id)
.single();
if (error) throw error;
if (!data) return res.status(404).json({ error: 'Usuário não encontrado' });
res.json(data);
} catch (error) {
console.error('Error fetching user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rota para criar um novo usuário
app.post('/api/users', async (req, res) => {
const { username, email, password_plaintext, tipo = 'comum' } = req.body;
try {
// Verifica se já existe usuário com mesmo username ou email
const { data: existingUsers, error: userError } = await supabase
.from('users')
.select('id')
.or(`username.eq.${username},email.eq.${email}`);
if (userError) throw userError;
if (existingUsers && existingUsers.length > 0) {
return res.status(400).json({
error: 'Usuário ou email já cadastrado'
});
}
// Insere novo usuário
const { data: newUser, error: insertError } = await supabase
.from('users')
.insert([{
username,
email,
password_plaintext,
tipo,
created_at: new Date().toISOString()
}])
.select('*')
.single();
if (insertError) throw insertError;
res.json(newUser);
} catch (err) {
console.error('Erro ao cadastrar usuário:', err);
res.status(500).json({ error: 'Erro interno do servidor' });
}
});
// Rota para atualizar um usuário
app.put('/api/users/:id', async (req, res) => {
try {
const { id } = req.params;
const { username, email, password_plaintext, tipo } = req.body;
if (!username || !email) {
return res.status(400).json({ error: 'Nome de usuário e e-mail são obrigatórios' });
}
const updateData = {
username,
email,
updated_at: new Date().toISOString(),
...(tipo && { tipo }),
...(password_plaintext && { password_plaintext })
};
const { data, error } = await supabase
.from('users')
.update(updateData)
.eq('id', id)
.select('*')
.single();
if (error) throw error;
res.json(data);
} catch (error) {
console.error('Error updating user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rota para excluir um usuário
app.delete('/api/users/:id', async (req, res) => {
try {
const { id } = req.params;
// Verifica se o usuário existe
const { data: existingUser, error: userError } = await supabase
.from('users')
.select('id')
.eq('id', id)
.single();
if (userError || !existingUser) {
return res.status(404).json({ error: 'Usuário não encontrado' });
}
// Exclui o usuário
const { error: deleteError } = await supabase
.from('users')
.delete()
.eq('id', id);
if (deleteError) throw deleteError;
res.json({ success: true });
} catch (err) {
console.error('Erro ao excluir usuário:', err);
res.status(500).json({ error: 'Erro interno do servidor' });
}
});
// Rota de cadastro
app.post('/api/register', async (req, res) => {
const { username, email, aniversario, password_plaintext } = req.body;
try {
// Verifica se já existe usuário com mesmo username ou email
const { data: existingUsers, error: userError } = await supabase
.from('users')
.select('id')
.or(`username.eq.${username},email.eq.${email}`);
if (userError) {
throw userError;
}
if (existingUsers && existingUsers.length > 0) {
return res.status(400).json({
error: 'Usuário ou email já cadastrado'
});
}
// Insere novo usuário com tipo "comum"
const { data: newUser, error: insertError } = await supabase
.from('users')
.insert([{
username,
email,
aniversario,
password_plaintext, // Em produção: criptografar
tipo: 'comum',
created_at: new Date().toISOString()
}])
.select('id, username, email, aniversario, created_at')
.single();
if (insertError) {
throw insertError;
}
res.json({
success: true,
user: newUser
});
} catch (err) {
console.error('Erro ao cadastrar usuário:', err);
res.status(500).json({ error: 'Erro interno do servidor' });
}
});
// ... (o restante do código permanece o mesmo)
// Rota de login simplificada (SEM HASH - APENAS PARA DESENVOLVIMENTO)
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;
try {
const { data: user, error } = await supabase
.from('users')
.select('id, username, email, password_plaintext, tipo')
.eq('username', username)
.single();
if (error || !user || user.password_plaintext !== password) {
return res.status(401).json({ error: 'Credenciais inválidas' });
}
// Se a autenticação for bem-sucedida, define o cookie com os dados do usuário
const userData = {
id: user.id,
username: user.username,
email: user.email,
tipo: user.tipo
};
res.cookie('userData', JSON.stringify(userData), {
httpOnly: true, // Evita que o cookie seja acessado via JavaScript
secure: false, // Coloque true se estiver usando HTTPS em produção
maxAge: 60 * 60 * 1000, // Expira após 1 hora
});
res.json({
success: true,
user: userData
});
} catch (err) {
console.error('Erro ao fazer login:', err);
res.status(500).json({ error: 'Erro interno do servidor' });
}
});
app.post('/api/verifica-usuario', async (req, res) => {
const { username } = req.body;
try {
const { data: user, error } = await supabase
.from('users')
.select('id')
.eq('username', username)
.single();
if (error || !user) {
return res.json({ exists: false });
}
res.json({ exists: true });
} catch (err) {
console.error('Erro ao verificar usuário:', err);
res.status(500).json({ exists: false });
}
});
// API para o frontend (Agendamento)
app.get('/api/categories', async (req, res) => {
try {
const { data, error } = await supabase
.from('categories')
.select('id, name, imagem_category') // Adicionar imagem_category
.order('name', { ascending: true });
if (error) throw error;
res.json(data);
} catch (error) {
console.error('Error fetching categories:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/services/:categoryId', async (req, res) => {
try {
const { categoryId } = req.params;
const { data, error } = await supabase
.from('services')
.select('id, name, price, duration, imagem_service') // Adicionar imagem_service
.eq('category_id', categoryId)
.order('name', { ascending: true });
if (error) throw error;
res.json(data);
} catch (error) {
console.error('Error fetching services:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/employees/:serviceId', async (req, res) => {
try {
const { serviceId } = req.params;
const { data, error } = await supabase
.from('employee_services')
.select('employees(*)')
.eq('service_id', serviceId);
if (error) throw error;
const employees = data.map(item => item.employees);
res.json(employees);
} catch (error) {
console.error('Error fetching employees:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/available-times', async (req, res) => {
try {
const { employeeId, date, duration } = req.query;
console.log('Parâmetros recebidos:', { employeeId, date, duration });
const dateObj = new Date(date);
const dayOfWeek = dateObj.getDay(); // 0-6 (Domingo-Sábado)
console.log('Dia da semana calculado:', dayOfWeek)
const { data: schedule, error: scheduleError } = await supabase
.from('work_schedules')
.select('*')
.eq('employee_id', employeeId)
.eq('day_of_week', dayOfWeek)
.single();
if (scheduleError || !schedule || !schedule.is_available) {
return res.json([]);
}
const { data: appointments, error: appointmentsError } = await supabase
.from('appointments')
.select('*')
.eq('employee_id', employeeId)
.eq('appointment_date', date)
.order('start_time', { ascending: true });
if (appointmentsError) throw appointmentsError;
const workStart = new Date(`${date}T${schedule.start_time}`);
const workEnd = new Date(`${date}T${schedule.end_time}`);
const interval = 15 * 60 * 1000;
const durationMs = duration * 60 * 1000;
let currentSlot = new Date(workStart);
const availableSlots = [];
while (currentSlot.getTime() + durationMs <= workEnd.getTime()) {
const slotStart = new Date(currentSlot);
const slotEnd = new Date(slotStart.getTime() + durationMs);
const isAvailable = !appointments.some(appointment => {
const apptStart = new Date(`${date}T${appointment.start_time}`);
const apptEnd = new Date(`${date}T${appointment.end_time}`);
return (
(slotStart >= apptStart && slotStart < apptEnd) ||
(slotEnd > apptStart && slotEnd <= apptEnd) ||
(slotStart <= apptStart && slotEnd >= apptEnd)
);
});
if (isAvailable) {
availableSlots.push({
start: slotStart.toTimeString().substring(0, 5),
end: slotEnd.toTimeString().substring(0, 5)
});
}
currentSlot = new Date(currentSlot.getTime() + interval);
}
res.json(availableSlots);
} catch (error) {
console.error('Error fetching available times:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/api/appointments', async (req, res) => {
try {
const { client_name, client_email, client_phone, service_id, employee_id, date, start_time, end_time , final_price , coupon_code , original_price } = req.body;
const { data, error } = await supabase
.from('appointments')
.insert([{
client_name,
client_email,
client_phone,
service_id,
employee_id,
appointment_date: date,
start_time,
end_time,
final_price,
coupon_code,
original_price,
status: 'confirmed'
}])
.select();
if (error) throw error;
res.status(201).json(data[0]);
} catch (error) {
console.error('Error creating appointment:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rota para obter agendamentos por email (área do cliente)
app.get('/api/logado/appointments', async (req, res) => {
try {
const { email } = req.query;
// Busca os agendamentos do cliente
const { data, error } = await supabase
.from('appointments')
.select(`
id,
client_name,
client_email,
client_phone,
appointment_date,
start_time,
end_time,
status,
created_at,
services(name, price),
employees(name)
`)
.eq('client_email', email)
.order('appointment_date', { ascending: true })
.order('start_time', { ascending: true });
if (error) throw error;
// Formata os dados para resposta
const formattedData = data.map(item => ({
id: item.id,
date: item.appointment_date,
start_time: item.start_time,
end_time: item.end_time,
status: item.status,
created_at: item.created_at,
service_name: item.services?.name,
service_price: item.services?.price,
professional_name: item.employees?.name,
client_name: item.client_name,
client_email: item.client_email,
client_phone: item.client_phone
}));
res.json(formattedData);
} catch (error) {
console.error('Error fetching client appointments:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rotas para agendamentos (admin)
app.get('/api/admin/appointments', async (req, res) => {
try {
const { search, date, employee } = req.query;
let query = supabase
.from('appointments')
.select(`
*,
services:service_id (name, price),
employees:employee_id (name)
`)
.order('appointment_date', { ascending: true })
.order('start_time', { ascending: true });
if (search) {
query = query.or(`client_name.ilike.%${search}%,client_email.ilike.%${search}%,client_phone.ilike.%${search}%`);
}
if (date) {
// Converte DD-MM-YYYY para YYYY-MM-DD (formato do Supabase)
const [day, month, year] = date.split('-');
const dbDate = `${year}-${month}-${day}`;
query = query.eq('appointment_date', dbDate);
}
if (employee) {
// Filtrar usando a relação com employees
query = query.ilike('employees.name', `%${employee}%`);
}
const { data, error } = await query;
if (error) throw error;
// Filtro adicional para funcionários (caso o filtro do Supabase não funcione)
let filteredData = data;
if (employee) {
filteredData = data.filter(appt =>
appt.employees?.name?.toLowerCase().includes(employee.toLowerCase())
);
}
res.json(filteredData);
} catch (error) {
console.error('Error fetching appointments:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rota para obter detalhes de um agendamento específico
app.get('/api/admin/appointments/:id', async (req, res) => {
try {
const { id } = req.params;
const { data, error } = await supabase
.from('appointments')
.select(`
*,
services(name, price),
employees(name)
`)
.eq('id', id)
.single();
if (error) throw error;
if (!data) return res.status(404).json({ error: 'Agendamento não encontrado' });
res.json({
id: data.id,
client_name: data.client_name,
service: data.services?.name || 'N/A',
professional: data.employees?.name || 'N/A',
date: data.appointment_date, // Formato YYYY-MM-DD
start_time: data.start_time, // Formato HH:MM:SS
end_time: data.end_time, // Formato HH:MM:SS
status: data.status,
price: data.services?.price || 0
});
} catch (error) {
console.error('Error fetching appointment:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rota para marcar agendamento como concluído
app.put('/api/admin/appointments/:id/complete', async (req, res) => {
try {
const { id } = req.params;
const { data, error } = await supabase
.from('appointments')
.update({
status: 'completed',
completed_at: new Date().toISOString()
})
.eq('id', id)
.select();
if (error) {
console.error('Supabase error:', error);
throw error;
}
if (!data || data.length === 0) {
return res.status(404).json({ error: 'Agendamento não encontrado' });
}
res.json(data[0]);
} catch (error) {
console.error('Error in API:', error);
res.status(500).json({
error: 'Internal server error',
details: error.message
});
}
});
app.put('/api/admin/appointments/:id/cancel', async (req, res) => {
try {
const { id } = req.params;
const { data, error } = await supabase
.from('appointments')
.update({ status: 'canceled' })
.eq('id', id)
.select();
if (error) throw error;
res.json(data[0]);
} catch (error) {
console.error('Error canceling appointment:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Rotas para categorias
app.get('/api/admin/categories', async (req, res) => {
try {
const { data, error } = await supabase