Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ app.get('/api/products', async (_, res) => {
res.json(result.rows);
});

app.post('/api/login', (req, res) => {
const { username, password } = req.body || {};

const validUser = process.env.ADMIN_USER || process.env.PGUSER || 'postgres';
const validPassword = process.env.ADMIN_PASSWORD || process.env.PGPASSWORD || 'postgres';

if (username === validUser && password === validPassword) {
res.json({ token: 'ok', name: 'Administrador' });
return;
}

res.status(401).json({ message: 'Credenciais inválidas' });
});

app.post('/api/products', async (req, res) => {
const { name, price, category, description, active = true } = req.body;
const query =
Expand Down
110 changes: 96 additions & 14 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ import {
FileText,
LogOut
} from 'lucide-react';
import { signInWithPopup, onAuthStateChanged, signOut } from 'firebase/auth';
import { auth, googleProvider } from './config/firebase';
import { productService } from './services/productService';
import { orderService } from './services/orderService';
import { authService } from './services/authService';
import { MenuView } from './components/Client/MenuView';
import { CartView } from './components/Client/CartView';
import { SuccessView } from './components/Client/SuccessView';
Expand All @@ -33,13 +32,20 @@ function App() {
const [adminTab, setAdminTab] = useState('dashboard');
const [cart, setCart] = useState({});
const [customer, setCustomer] = useState(initialCustomer);
const [loginForm, setLoginForm] = useState({ username: '', password: '' });
const [loginError, setLoginError] = useState('');

useEffect(() => {
const unsubAuth = onAuthStateChanged(auth, setUser);
const savedSession = localStorage.getItem('adminSession');
if (savedSession) {
const parsedSession = JSON.parse(savedSession);
setUser(parsedSession);
setView('admin');
}

const unsubProd = productService.subscribe(setProducts);
const unsubOrders = orderService.subscribeAll(setOrders);
return () => {
unsubAuth();
unsubProd();
unsubOrders();
};
Expand Down Expand Up @@ -91,17 +97,25 @@ function App() {
setView('success');
};

const handleLogin = async () => {
const handleLogin = async (event) => {
event?.preventDefault();
setLoginError('');

try {
await signInWithPopup(auth, googleProvider);
const session = await authService.login(loginForm.username, loginForm.password);
const sessionData = { ...session, username: loginForm.username };
localStorage.setItem('adminSession', JSON.stringify(sessionData));
setUser(sessionData);
setView('admin');
} catch (error) {
alert('Erro ao logar: ' + error.message);
setLoginError(error.message || 'Falha ao autenticar');
}
};

const logout = () => {
signOut(auth);
localStorage.removeItem('adminSession');
setUser(null);
setLoginForm({ username: '', password: '' });
setView('menu');
};

Expand Down Expand Up @@ -152,11 +166,11 @@ function App() {
<div className="p-4 border-t border-gray-800">
<div className="flex items-center gap-3 mb-4">
<div className="w-8 h-8 rounded-full bg-gray-700 flex items-center justify-center text-sm font-bold">
{user.displayName?.[0] || 'U'}
{user.name?.[0]?.toUpperCase() || user.username?.[0]?.toUpperCase() || 'U'}
</div>
<div className="overflow-hidden">
<p className="text-sm font-bold truncate">{user.displayName}</p>
<p className="text-xs text-gray-500 truncate">{user.email}</p>
<p className="text-sm font-bold truncate">{user.name || 'Administrador'}</p>
<p className="text-xs text-gray-500 truncate">{user.username || 'admin'}</p>
</div>
</div>
<button
Expand Down Expand Up @@ -203,9 +217,17 @@ function App() {
</thead>
<tbody className="divide-y">
{orders.map((order) => (
<tr key={order.id}>
<tr key={order.id}>
<td className="p-3 text-gray-500">
{order.createdAt ? new Date(order.createdAt.seconds * 1000).toLocaleString() : order.dateString}
{
order.createdAt?.seconds
? new Date(order.createdAt.seconds * 1000).toLocaleString()
: order.createdAt
? new Date(order.createdAt).toLocaleString()
: order.timestamp
? new Date(order.timestamp).toLocaleString()
: order.dateString
}
</td>
<td className="p-3 font-medium">{order.name}</td>
<td className="p-3 uppercase text-xs font-bold">{order.type}</td>
Expand Down Expand Up @@ -248,7 +270,13 @@ function App() {
</div>
</div>
<div className="flex items-center gap-3 text-gray-400">
<button onClick={handleLogin} className="hover:text-red-600 transition-colors">
<button
onClick={() => {
setView('login');
setLoginError('');
}}
className="hover:text-red-600 transition-colors"
>
<User size={20} />
</button>
<button onClick={() => setView('grill')} className="hover:text-red-600 transition-colors">
Expand All @@ -259,6 +287,60 @@ function App() {
</header>

<main className="max-w-lg mx-auto p-4">
{view === 'login' && (
<form onSubmit={handleLogin} className="bg-white rounded-xl shadow-sm p-6 space-y-4">
<div>
<h2 className="text-lg font-bold text-gray-800">Acesso do administrador</h2>
<p className="text-sm text-gray-500">Use usuário e senha definidos no banco (PGUSER/PGPASSWORD).</p>
</div>

{loginError && <div className="text-sm text-red-600 bg-red-50 border border-red-100 p-3 rounded-lg">{loginError}</div>}

<div className="space-y-2">
<label className="text-sm font-semibold text-gray-700" htmlFor="username">
Usuário
</label>
<input
id="username"
type="text"
value={loginForm.username}
onChange={(e) => setLoginForm((prev) => ({ ...prev, username: e.target.value }))}
className="w-full border rounded-lg p-3 focus:ring-2 focus:ring-red-500 focus:outline-none"
placeholder="postgres"
/>
</div>

<div className="space-y-2">
<label className="text-sm font-semibold text-gray-700" htmlFor="password">
Senha
</label>
<input
id="password"
type="password"
value={loginForm.password}
onChange={(e) => setLoginForm((prev) => ({ ...prev, password: e.target.value }))}
className="w-full border rounded-lg p-3 focus:ring-2 focus:ring-red-500 focus:outline-none"
placeholder="senha do banco"
/>
</div>

<div className="flex gap-3">
<button
type="submit"
className="flex-1 bg-red-600 text-white py-3 rounded-lg font-semibold hover:bg-red-700 transition-colors"
>
Entrar
</button>
<button
type="button"
onClick={() => setView('menu')}
className="flex-1 border border-gray-300 text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-50 transition-colors"
>
Cancelar
</button>
</div>
</form>
)}
{view === 'menu' && <MenuView products={products} cart={cart} onUpdateCart={updateCart} onProceed={() => setView('cart')} />}
{view === 'cart' && (
<CartView
Expand Down
6 changes: 3 additions & 3 deletions src/App.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
test('renderiza a marca Datony no topo', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
const heading = screen.getByText(/Datony/i);
expect(heading).toBeInTheDocument();
});
68 changes: 44 additions & 24 deletions src/config/apiClient.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:4000';
const resolveBaseUrl = () => {
if (process.env.REACT_APP_API_BASE_URL) {
return process.env.REACT_APP_API_BASE_URL;
}

if (typeof window === 'undefined') {
return 'http://localhost:4000';
}

if (window.location.port && window.location.port !== '3000') {
return `${window.location.origin}`;
}

return 'http://localhost:4000';
};

const API_BASE_URL = resolveBaseUrl();

const defaultHeaders = {
'Content-Type': 'application/json'
Expand All @@ -12,31 +28,35 @@ const handleResponse = async (response) => {
return response.json();
};

const request = async (path, options) => {
try {
const response = await fetch(`${API_BASE_URL}${path}`, options);
return await handleResponse(response);
} catch (error) {
console.error('Erro ao comunicar com a API', error);
throw new Error('Não foi possível conectar à API. Verifique se o servidor está ativo.');
}
};

export const apiClient = {
get: async (path) => handleResponse(await fetch(`${API_BASE_URL}${path}`)),
get: async (path) => request(path),
post: async (path, body) =>
handleResponse(
await fetch(`${API_BASE_URL}${path}`, {
method: 'POST',
headers: defaultHeaders,
body: JSON.stringify(body)
})
),
request(path, {
method: 'POST',
headers: defaultHeaders,
body: JSON.stringify(body)
}),
put: async (path, body) =>
handleResponse(
await fetch(`${API_BASE_URL}${path}`, {
method: 'PUT',
headers: defaultHeaders,
body: JSON.stringify(body)
})
),
request(path, {
method: 'PUT',
headers: defaultHeaders,
body: JSON.stringify(body)
}),
patch: async (path, body) =>
handleResponse(
await fetch(`${API_BASE_URL}${path}`, {
method: 'PATCH',
headers: defaultHeaders,
body: JSON.stringify(body)
})
),
delete: async (path) => handleResponse(await fetch(`${API_BASE_URL}${path}`, { method: 'DELETE' }))
request(path, {
method: 'PATCH',
headers: defaultHeaders,
body: JSON.stringify(body)
}),
delete: async (path) => request(path, { method: 'DELETE' })
};
11 changes: 11 additions & 0 deletions src/services/authService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { apiClient } from '../config/apiClient';

export const authService = {
async login(username, password) {
const response = await apiClient.post('/api/login', { username, password });
return {
token: response.token,
name: response.name || 'Administrador'
};
}
};
10 changes: 7 additions & 3 deletions src/services/orderService.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ export const orderService = {
let cancelled = false;

const load = async () => {
const data = await apiClient.get('/api/orders');
if (!cancelled) {
callback(data.map(normalizeOrder));
try {
const data = await apiClient.get('/api/orders');
if (!cancelled) {
callback(data.map(normalizeOrder));
}
} catch (error) {
console.error('Erro ao carregar pedidos', error);
}
};

Expand Down
10 changes: 7 additions & 3 deletions src/services/productService.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ export const productService = {
let cancelled = false;

const load = async () => {
const data = await apiClient.get('/api/products');
if (!cancelled) {
callback(data.map(normalizeProduct));
try {
const data = await apiClient.get('/api/products');
if (!cancelled) {
callback(data.map(normalizeProduct));
}
} catch (error) {
console.error('Erro ao carregar produtos', error);
}
};

Expand Down