Compare commits
12 Commits
Author | SHA1 | Date |
---|---|---|
Steve White | e0f7af5e88 | |
Steve White | 74502b1077 | |
Steve White | c400ccc400 | |
Steve White | efa24c3f84 | |
Steve White | 2e598968ac | |
Steve White | 165e4965df | |
Steve White | bd32bfaae5 | |
Steve White | 31eb7c0439 | |
Steve White | 158d52dab4 | |
Steve White | ca301c3108 | |
Steve White | 5f3b592724 | |
Steve White | 3f33d5fda4 |
|
@ -0,0 +1,5 @@
|
||||||
|
node_modules
|
||||||
|
.git
|
||||||
|
*.log
|
||||||
|
build
|
||||||
|
.DS_Store
|
5
.env
5
.env
|
@ -1,5 +1,2 @@
|
||||||
# URL of the API
|
REACT_APP_API_URL=http://nebula1:8080
|
||||||
REACT_APP_API_URL=http://localhost:8080
|
|
||||||
|
|
||||||
# Base URL of the webapp
|
|
||||||
REACT_APP_BASE_URL="/"
|
|
||||||
|
|
|
@ -0,0 +1,7 @@
|
||||||
|
FROM node:18-alpine AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install
|
||||||
|
COPY .env .
|
||||||
|
COPY . .
|
||||||
|
CMD ["npm", "run", "build"]
|
|
@ -0,0 +1,23 @@
|
||||||
|
# Stage 1: Install dependencies
|
||||||
|
FROM node:14 AS build-stage
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package.json and package-lock.json first to leverage caching
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
# Copy the rest of your application code
|
||||||
|
COPY .env .
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Build the application
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Final stage: Use a minimal base image
|
||||||
|
FROM alpine:latest
|
||||||
|
|
||||||
|
# Copy the build output from the previous stage
|
||||||
|
COPY --from=build-stage /app/build ./build
|
|
@ -0,0 +1,20 @@
|
||||||
|
# Dockerfile.create
|
||||||
|
FROM node:14 AS builder
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package.json and package-lock.json
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm install
|
||||||
|
RUN npm install -g serve
|
||||||
|
|
||||||
|
# Copy the rest of the application code
|
||||||
|
COPY . .
|
||||||
|
COPY .env .
|
||||||
|
|
||||||
|
RUN npm build .
|
||||||
|
|
||||||
|
CMD ["serve", "-s", "build"]
|
|
@ -0,0 +1,4 @@
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY build /usr/share/nginx/html
|
||||||
|
EXPOSE 80
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
|
@ -0,0 +1,18 @@
|
||||||
|
# Dockerfile.update
|
||||||
|
FROM node:14
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package.json and package-lock.json
|
||||||
|
COPY package*.json ./
|
||||||
|
ENV REACT_APP_API_URL=http://zbox.local:8080
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
# Copy the rest of the application code
|
||||||
|
COPY . .
|
||||||
|
COPY .env .
|
||||||
|
|
||||||
|
CMD ["npm", "run", "build"]
|
18
README.md
18
README.md
|
@ -27,3 +27,21 @@ This is the frontend application for the Boxes App, built with React. It allows
|
||||||
1. **Clone the repository:**
|
1. **Clone the repository:**
|
||||||
```bash
|
```bash
|
||||||
git clone git@gitea.r8z.us:stwhite/boxes-fe.git
|
git clone git@gitea.r8z.us:stwhite/boxes-fe.git
|
||||||
|
|
||||||
|
2. create the docker builder
|
||||||
|
```bash
|
||||||
|
docker build -f Dockerfile.build -t boxes-fe-builder .
|
||||||
|
```
|
||||||
|
|
||||||
|
3. build the application using the docker builder
|
||||||
|
```bash
|
||||||
|
docker run box-builder:latest
|
||||||
|
docker container create --name tmp-con boxes-fe-builder -- sleep 1200
|
||||||
|
docker cp tmp-con:/app/build ./boxes-fe/build
|
||||||
|
docker rm tmp-con
|
||||||
|
```
|
||||||
|
|
||||||
|
4. copy the appliction to the boxes-api /build directory
|
||||||
|
```bash
|
||||||
|
cp -r ./boxes-fe/build/* ../boxes-api/build/
|
||||||
|
```
|
|
@ -0,0 +1,7 @@
|
||||||
|
#!/bin/bash
|
||||||
|
# Create teh react-builder image
|
||||||
|
docker build -f Dockerfile.create -t react-builder:latest .
|
||||||
|
# Run the react-builder image with local build/ dir mounted
|
||||||
|
docker run -v $(pwd)/build:/app/build react-builder:latest
|
||||||
|
# create the nginx container:
|
||||||
|
docker build --no-cache -f Dockerfile.nginx -t boxes-fe:latest .
|
|
@ -16,6 +16,7 @@
|
||||||
"@testing-library/react": "^13.4.0",
|
"@testing-library/react": "^13.4.0",
|
||||||
"@testing-library/user-event": "^13.5.0",
|
"@testing-library/user-event": "^13.5.0",
|
||||||
"axios": "^1.7.7",
|
"axios": "^1.7.7",
|
||||||
|
"lucide-react": "^0.454.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-router-dom": "^6.26.2",
|
"react-router-dom": "^6.26.2",
|
||||||
|
@ -13981,6 +13982,15 @@
|
||||||
"yallist": "^3.0.2"
|
"yallist": "^3.0.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/lucide-react": {
|
||||||
|
"version": "0.454.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.454.0.tgz",
|
||||||
|
"integrity": "sha512-hw7zMDwykCLnEzgncEEjHeA6+45aeEzRYuKHuyRSOPkhko+J3ySGjGIzu+mmMfDFG1vazHepMaYFYHbTFAZAAQ==",
|
||||||
|
"license": "ISC",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/lz-string": {
|
"node_modules/lz-string": {
|
||||||
"version": "1.5.0",
|
"version": "1.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
|
||||||
|
|
|
@ -11,6 +11,7 @@
|
||||||
"@testing-library/react": "^13.4.0",
|
"@testing-library/react": "^13.4.0",
|
||||||
"@testing-library/user-event": "^13.5.0",
|
"@testing-library/user-event": "^13.5.0",
|
||||||
"axios": "^1.7.7",
|
"axios": "^1.7.7",
|
||||||
|
"lucide-react": "^0.454.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-router-dom": "^6.26.2",
|
"react-router-dom": "^6.26.2",
|
||||||
|
|
|
@ -24,7 +24,7 @@
|
||||||
work correctly both with client-side routing and a non-root public URL.
|
work correctly both with client-side routing and a non-root public URL.
|
||||||
Learn how to configure a non-root public URL by running `npm run build`.
|
Learn how to configure a non-root public URL by running `npm run build`.
|
||||||
-->
|
-->
|
||||||
<title>React App</title>
|
<title>Boxes</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||||
|
|
38
src/App.js
38
src/App.js
|
@ -8,7 +8,9 @@ import Items from './components/Items';
|
||||||
import Navbar from './components/Navbar'; // Correct import here
|
import Navbar from './components/Navbar'; // Correct import here
|
||||||
import Admin from './components/Admin'; // Correct import here
|
import Admin from './components/Admin'; // Correct import here
|
||||||
import { createContext } from 'react';
|
import { createContext } from 'react';
|
||||||
|
import ErrorBoundary from './components/ErrorBoundary';
|
||||||
import './styles.css'
|
import './styles.css'
|
||||||
|
import { EnhancedThemeProvider } from './components/themeProvider';
|
||||||
|
|
||||||
export const AppContext = createContext();
|
export const AppContext = createContext();
|
||||||
export const PRIMARY_COLOR = '#333';
|
export const PRIMARY_COLOR = '#333';
|
||||||
|
@ -25,12 +27,16 @@ function App() {
|
||||||
}, [token]);
|
}, [token]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppContext.Provider value={{ token, setToken }}>
|
<EnhancedThemeProvider>
|
||||||
<Router>
|
<AppContext.Provider value={{ token, setToken }}>
|
||||||
<Navbar />
|
<ErrorBoundary>
|
||||||
<AppRoutes token={token} setToken={setToken} />
|
<Router>
|
||||||
</Router>
|
<Navbar />
|
||||||
</AppContext.Provider>
|
<AppRoutes token={token} setToken={setToken} />
|
||||||
|
</Router>
|
||||||
|
</ErrorBoundary>
|
||||||
|
</AppContext.Provider>
|
||||||
|
</EnhancedThemeProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -40,24 +46,24 @@ function AppRoutes({ token, setToken }) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<Login setToken={setToken} />} />
|
<Route path="/api/v1/login" element={<Login setToken={setToken} />} />
|
||||||
<Route
|
<Route
|
||||||
path="/boxes"
|
path="/api/v1/boxes"
|
||||||
element={token ? <Boxes token={token} /> : <Navigate to="/login" replace />}
|
element={token ? <Boxes token={token} /> : <Navigate to="/api/v1/login" replace />}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/items"
|
path="/api/v1/items"
|
||||||
element={token ? <Items token={token} /> : <Navigate to="/login" replace />}
|
element={token ? <Items token={token} /> : <Navigate to="/api/v1/login" replace />}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/boxes/:id/items"
|
path="/api/v1/boxes/:id/items"
|
||||||
element={token ? <Items box_id={id} token={token} /> : <Navigate to="/login" replace />}
|
element={token ? <Items box_id={id} token={token} /> : <Navigate to="/api/v1/login" replace />}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/admin"
|
path="/api/v1/admin"
|
||||||
element={token ? <Admin token={token}/> : <Navigate to="/login" replace />}
|
element={token ? <Admin token={token}/> : <Navigate to="/api/v1/login" replace />}
|
||||||
/>
|
/>
|
||||||
<Route path="*" element={<Navigate to={token ? "/boxes" : "/login"} replace />} />
|
<Route path="*" element={<Navigate to={token ? "/api/v1/boxes" : "/api/v1/login"} replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
|
@ -1,29 +0,0 @@
|
||||||
# Use an official Node runtime as the base image
|
|
||||||
FROM node:14 as build
|
|
||||||
|
|
||||||
# Set the working directory in the container
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy package.json and package-lock.json
|
|
||||||
COPY package*.json ./
|
|
||||||
|
|
||||||
# Install dependencies
|
|
||||||
RUN npm install
|
|
||||||
|
|
||||||
# Copy the rest of the application code
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
# Build the app
|
|
||||||
RUN npm run build
|
|
||||||
|
|
||||||
# Use nginx to serve the static files
|
|
||||||
FROM nginx:alpine
|
|
||||||
|
|
||||||
# Copy the build output to replace the default nginx contents
|
|
||||||
COPY --from=build /app/build /usr/share/nginx/html
|
|
||||||
|
|
||||||
# Expose port 80
|
|
||||||
EXPOSE 80
|
|
||||||
|
|
||||||
# Start nginx
|
|
||||||
CMD ["nginx", "-g", "daemon off;"]
|
|
|
@ -1,235 +1,309 @@
|
||||||
// src/components/Admin.js
|
|
||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import axios from 'axios';
|
// import axios from 'axios';
|
||||||
import { Link, useNavigate } from 'react-router-dom';
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
||||||
import './Admin.css'; // Import the CSS file
|
import './Admin.css';
|
||||||
|
import { useApiCall } from './hooks/useApiCall';
|
||||||
|
import { api } from '../services/api';
|
||||||
import {
|
import {
|
||||||
Typography,
|
Typography,
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
TableCell,
|
TableCell,
|
||||||
TableContainer,
|
TableContainer,
|
||||||
TableHead,
|
TableHead,
|
||||||
TableRow,
|
TableRow,
|
||||||
Paper,
|
Paper,
|
||||||
Button,
|
Button,
|
||||||
Alert,
|
Alert,
|
||||||
Container,
|
Container,
|
||||||
Box,
|
Box,
|
||||||
TextField,
|
TextField,
|
||||||
Tab
|
CircularProgress,
|
||||||
} from '@mui/material';
|
Tab,
|
||||||
|
Tabs
|
||||||
|
} from '@mui/material';
|
||||||
|
|
||||||
export default function Admin() {
|
export default function Admin() {
|
||||||
const [users, setUsers] = useState([]);
|
const [users, setUsers] = useState([]);
|
||||||
|
const [tags, setTags] = useState([]);
|
||||||
const [username, setUsername] = useState('');
|
const [username, setUsername] = useState('');
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
|
const [activeTab, setActiveTab] = useState(0);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const fileInputRef = useRef(null);
|
const fileInputRef = useRef(null);
|
||||||
|
|
||||||
|
const { execute: fetchUsers, loading: loadingUsers, error: usersError } = useApiCall();
|
||||||
|
const { execute: fetchTags, loading: loadingTags, error: tagsError } = useApiCall();
|
||||||
|
const { execute: createUser, loading: creatingUser, error: createError } = useApiCall();
|
||||||
|
const { execute: deleteUser, loading: deletingUser, error: deleteError } = useApiCall();
|
||||||
|
const { execute: deleteTag, loading: deletingTag, error: deleteTagError } = useApiCall();
|
||||||
|
const { execute: backupDB, loading: backingUp, error: backupError } = useApiCall();
|
||||||
|
const { execute: restoreDB, loading: restoring, error: restoreError } = useApiCall();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
axios.get(`${process.env.REACT_APP_API_URL}/admin/user`, {
|
const getInitialData = async () => {
|
||||||
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
|
try {
|
||||||
})
|
const [usersResponse, tagsResponse] = await Promise.all([
|
||||||
.then(response => {
|
fetchUsers(() => api.admin.getUsers(localStorage.getItem('token'))),
|
||||||
setUsers(response.data);
|
fetchTags(() => api.tags.getAll(localStorage.getItem('token')))
|
||||||
})
|
]);
|
||||||
.catch(error => {
|
setUsers(usersResponse.data);
|
||||||
console.error(error);
|
setTags(tagsResponse.data);
|
||||||
});
|
} catch (err) {}
|
||||||
|
};
|
||||||
|
getInitialData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const fetchUsers = async () => {
|
|
||||||
try {
|
|
||||||
const response = await axios.get(`${process.env.REACT_APP_API_URL}/admin/user`, {
|
|
||||||
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
|
|
||||||
});
|
|
||||||
setUsers(response.data);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching users:', error);
|
|
||||||
// Optionally, set an error message
|
|
||||||
// setErrorMessage('Failed to fetch users. Please try again.');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCreateUser = async (e) => {
|
const handleCreateUser = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
try {
|
try {
|
||||||
const response = await axios.post(`${process.env.REACT_APP_API_URL}/admin/user`, {
|
const response = await createUser(() =>
|
||||||
username,
|
api.admin.createUser(
|
||||||
password,
|
localStorage.getItem('token'),
|
||||||
email
|
{ username, password, email }
|
||||||
}, {
|
)
|
||||||
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
|
);
|
||||||
});
|
|
||||||
setUsers([...users, response.data]);
|
setUsers([...users, response.data]);
|
||||||
setUsername('');
|
setUsername('');
|
||||||
setPassword('');
|
setPassword('');
|
||||||
setEmail('');
|
setEmail('');
|
||||||
} catch (error) {
|
} catch (err) {}
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteUser = async (id) => {
|
const handleDeleteUser = async (id) => {
|
||||||
try {
|
try {
|
||||||
await axios.delete(`${process.env.REACT_APP_API_URL}/admin/user/${id}`, {
|
await deleteUser(() =>
|
||||||
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
|
api.admin.deleteUser(localStorage.getItem('token'), id)
|
||||||
});
|
);
|
||||||
setUsers(users.filter(user => user.id !== id));
|
setUsers(users.filter(user => user.id !== id));
|
||||||
//setUsers(prevUsers => prevUsers.filter(user => user.id !== id));
|
} catch (err) {}
|
||||||
fetchUsers();
|
};
|
||||||
|
|
||||||
} catch (error) {
|
const handleDeleteTag = async (tagId) => {
|
||||||
console.error(error);
|
if (!window.confirm('Are you sure you want to delete this tag? This will remove it from all items.')) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await deleteTag(() =>
|
||||||
|
api.tags.delete(localStorage.getItem('token'), tagId)
|
||||||
|
);
|
||||||
|
setTags(tags.filter(tag => tag.ID !== tagId));
|
||||||
|
} catch (err) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleBackupDatabase = async () => {
|
const handleBackupDatabase = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await axios.get(`${process.env.REACT_APP_API_URL}/admin/db`, {
|
const response = await backupDB(() =>
|
||||||
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
|
api.admin.backupDB(localStorage.getItem('token'))
|
||||||
responseType: 'blob'
|
);
|
||||||
});
|
|
||||||
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
|
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = url;
|
||||||
a.download = 'database.db';
|
a.download = 'database.db';
|
||||||
a.click();
|
a.click();
|
||||||
} catch (error) {
|
} catch (err) {}
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRestoreDatabase = async (e) => {
|
const handleRestoreDatabase = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
if (!fileInputRef.current?.files?.[0]) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const file = fileInputRef.current.files[0];
|
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('database', file);
|
formData.append('database', fileInputRef.current.files[0]);
|
||||||
console.log("sending request to restore db")
|
|
||||||
|
await restoreDB(() =>
|
||||||
const token = localStorage.getItem('token');
|
api.admin.restoreDB(localStorage.getItem('token'), formData)
|
||||||
if (!token) {
|
);
|
||||||
throw new Error('No token found in local storage');
|
alert('Database restored successfully');
|
||||||
}
|
navigate('/admin');
|
||||||
|
} catch (err) {}
|
||||||
const response = await axios.post(`${process.env.REACT_APP_API_URL}/admin/db`, formData, {
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
'Content-Type': 'multipart/form-data'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.status === 200) {
|
|
||||||
alert('Database restored successfully');
|
|
||||||
navigate('/admin');
|
|
||||||
} else {
|
|
||||||
throw new Error(`Failed to restore database: ${response.statusText}`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container maxWidth="md">
|
<Container maxWidth="md">
|
||||||
<Typography variant="h4" gutterBottom>
|
<Typography variant="h4" gutterBottom>
|
||||||
Admin
|
Admin Dashboard
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
<Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}>
|
|
||||||
<Typography variant="h6" gutterBottom>
|
|
||||||
Add New User
|
|
||||||
</Typography>
|
|
||||||
<TextField
|
|
||||||
label="Username"
|
|
||||||
variant="outlined"
|
|
||||||
value={username}
|
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
|
||||||
sx={{ mr: 2 }}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
label="Password"
|
|
||||||
type="password"
|
|
||||||
variant="outlined"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
sx={{ mr: 2 }}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
label="Email"
|
|
||||||
variant="outlined"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
sx={{ mr: 2 }}
|
|
||||||
/>
|
|
||||||
<Button type="submit" sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary">
|
|
||||||
Add User
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<TableContainer component={Paper}>
|
{(usersError || createError || deleteError || backupError || restoreError || tagsError || deleteTagError) && (
|
||||||
<Table>
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
<TableHead>
|
{usersError?.message || createError?.message || deleteError?.message ||
|
||||||
<TableRow>
|
backupError?.message || restoreError?.message || tagsError?.message || deleteTagError?.message}
|
||||||
<TableCell>ID</TableCell>
|
</Alert>
|
||||||
<TableCell>Username</TableCell>
|
)}
|
||||||
<TableCell>Email</TableCell>
|
|
||||||
<TableCell>Actions</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
|
||||||
{users.map(user => (
|
|
||||||
<TableRow key={user.ID}>
|
|
||||||
<TableCell style={{ width: '30px' }}>{user.ID}</TableCell>
|
|
||||||
<TableCell style={{ width: '100px'}}>{user.username}</TableCell>
|
|
||||||
<TableCell style={{ width: '300px'}}>{user.email}</TableCell>
|
|
||||||
<TableCell>
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
color="error"
|
|
||||||
onClick={() => handleDeleteUser(user.ID)}
|
|
||||||
>
|
|
||||||
Delete User
|
|
||||||
</Button>
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
))}
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
|
||||||
</TableContainer>
|
|
||||||
|
|
||||||
<Box sx={{ mt: 4 }}>
|
<Tabs value={activeTab} onChange={(e, newValue) => setActiveTab(newValue)} sx={{ mb: 3 }}>
|
||||||
<Button
|
<Tab label="Users" />
|
||||||
variant="contained"
|
<Tab label="Tags" />
|
||||||
color="primary"
|
<Tab label="Database" />
|
||||||
onClick={handleBackupDatabase}
|
</Tabs>
|
||||||
sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
|
||||||
>
|
|
||||||
Backup Database
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button
|
{activeTab === 0 && (
|
||||||
variant="contained"
|
<>
|
||||||
color="secondary"
|
<Box component="form" onSubmit={handleCreateUser} sx={{ mb: 4 }}>
|
||||||
component="label"
|
<Typography variant="h6" gutterBottom>
|
||||||
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
Add New User
|
||||||
>
|
</Typography>
|
||||||
Restore Database
|
<TextField
|
||||||
<input
|
label="Username"
|
||||||
type="file"
|
variant="outlined"
|
||||||
hidden
|
value={username}
|
||||||
ref={fileInputRef}
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
onChange={handleRestoreDatabase}
|
sx={{ mr: 2 }}
|
||||||
/>
|
disabled={creatingUser}
|
||||||
</Button>
|
/>
|
||||||
</Box>
|
<TextField
|
||||||
|
label="Password"
|
||||||
|
type="password"
|
||||||
|
variant="outlined"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
sx={{ mr: 2 }}
|
||||||
|
disabled={creatingUser}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
label="Email"
|
||||||
|
variant="outlined"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
sx={{ mr: 2 }}
|
||||||
|
disabled={creatingUser}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
||||||
|
variant="contained"
|
||||||
|
disabled={creatingUser}
|
||||||
|
>
|
||||||
|
{creatingUser ? <CircularProgress size={24} /> : 'Add User'}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{loadingUsers ? (
|
||||||
|
<CircularProgress />
|
||||||
|
) : (
|
||||||
|
<TableContainer component={Paper}>
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>ID</TableCell>
|
||||||
|
<TableCell>Username</TableCell>
|
||||||
|
<TableCell>Email</TableCell>
|
||||||
|
<TableCell>Actions</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{users.map(user => (
|
||||||
|
<TableRow key={user.ID}>
|
||||||
|
<TableCell>{user.ID}</TableCell>
|
||||||
|
<TableCell>{user.username}</TableCell>
|
||||||
|
<TableCell>{user.email}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
color="error"
|
||||||
|
onClick={() => handleDeleteUser(user.ID)}
|
||||||
|
disabled={deletingUser}
|
||||||
|
>
|
||||||
|
{deletingUser ? <CircularProgress size={24} /> : 'Delete User'}
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 1 && (
|
||||||
|
<>
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Manage Tags
|
||||||
|
</Typography>
|
||||||
|
{loadingTags ? (
|
||||||
|
<CircularProgress />
|
||||||
|
) : (
|
||||||
|
<TableContainer component={Paper}>
|
||||||
|
<Table>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>Color</TableCell>
|
||||||
|
<TableCell>Name</TableCell>
|
||||||
|
<TableCell>Description</TableCell>
|
||||||
|
<TableCell>Actions</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{tags.map(tag => (
|
||||||
|
<TableRow key={tag.ID}>
|
||||||
|
<TableCell>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: 24,
|
||||||
|
height: 24,
|
||||||
|
backgroundColor: tag.color,
|
||||||
|
borderRadius: '50%'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{tag.name}</TableCell>
|
||||||
|
<TableCell>{tag.description}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
color="error"
|
||||||
|
onClick={() => handleDeleteTag(tag.ID)}
|
||||||
|
disabled={deletingTag}
|
||||||
|
>
|
||||||
|
{deletingTag ? <CircularProgress size={24} /> : 'Delete Tag'}
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 2 && (
|
||||||
|
<Box sx={{ mt: 4 }}>
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Database Management
|
||||||
|
</Typography>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={handleBackupDatabase}
|
||||||
|
sx={{ mr: 2, backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
||||||
|
disabled={backingUp}
|
||||||
|
>
|
||||||
|
{backingUp ? <CircularProgress size={24} /> : 'Backup Database'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
component="label"
|
||||||
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
||||||
|
disabled={restoring}
|
||||||
|
>
|
||||||
|
{restoring ? <CircularProgress size={24} /> : 'Restore Database'}
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
hidden
|
||||||
|
ref={fileInputRef}
|
||||||
|
onChange={handleRestoreDatabase}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
|
@ -1,93 +1,161 @@
|
||||||
// src/components/Boxes.js
|
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Container, Button, TextField, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';
|
import {
|
||||||
import { Delete as DeleteIcon } from '@mui/icons-material';
|
Container,
|
||||||
import { Link as RouterLink } from 'react-router-dom'; // Import Link from react-router-dom
|
Button,
|
||||||
import axios from 'axios';
|
TextField,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableContainer,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
Alert,
|
||||||
|
CircularProgress,
|
||||||
|
Avatar,
|
||||||
|
Box
|
||||||
|
} from '@mui/material';
|
||||||
|
import { Delete as DeleteIcon, Inventory as InventoryIcon } from '@mui/icons-material';
|
||||||
|
import { Link as RouterLink } from 'react-router-dom';
|
||||||
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
||||||
|
import { useApiCall } from './hooks/useApiCall';
|
||||||
|
import { api } from '../services/api';
|
||||||
|
|
||||||
export default function Boxes({ token }) {
|
export default function Boxes({ token }) {
|
||||||
const [boxes, setBoxes] = useState([]);
|
const [boxes, setBoxes] = useState([]);
|
||||||
const [newBoxName, setNewBoxName] = useState('');
|
const [newBoxName, setNewBoxName] = useState('');
|
||||||
const apiUrl = `${process.env.REACT_APP_API_URL}/boxes`;
|
|
||||||
|
|
||||||
const debugApi = () => {
|
const { execute: fetchBoxes, loading: loadingBoxes, error: boxesError } = useApiCall();
|
||||||
if (process.env.DEBUG_API) {
|
const { execute: createBox, loading: creatingBox, error: createError } = useApiCall();
|
||||||
console.log("URL is " + apiUrl);
|
const { execute: deleteBox, loading: deletingBox, error: deleteError } = useApiCall();
|
||||||
}
|
|
||||||
};
|
|
||||||
debugApi();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
//console.log('Token:' + token);
|
const getBoxes = async () => {
|
||||||
axios.get(`${process.env.REACT_APP_API_URL}/boxes`, {
|
try {
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
const response = await fetchBoxes(() =>
|
||||||
}).then(response => {
|
api.boxes.getAll(token)
|
||||||
setBoxes(response.data);
|
);
|
||||||
});
|
setBoxes(response.data);
|
||||||
|
} catch (err) {}
|
||||||
|
};
|
||||||
|
getBoxes();
|
||||||
}, [token]);
|
}, [token]);
|
||||||
|
|
||||||
// Log boxes state changes outside the useEffect
|
const handleCreateBox = async () => {
|
||||||
useEffect(() => {
|
if (!newBoxName.trim()) return;
|
||||||
//console.log('Boxes updated:', boxes);
|
|
||||||
}, [boxes]);
|
|
||||||
|
|
||||||
const handleCreateBox = () => {
|
try {
|
||||||
axios.post(`${process.env.REACT_APP_API_URL}/boxes`, { name: newBoxName }, {
|
const response = await createBox(() =>
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
api.boxes.create(token, { name: newBoxName })
|
||||||
}).then(response => {
|
);
|
||||||
setBoxes([...boxes, response.data]);
|
setBoxes([...boxes, response.data]);
|
||||||
setNewBoxName('');
|
setNewBoxName('');
|
||||||
});
|
} catch (err) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteBox = (id) => {
|
const handleDeleteBox = async (id) => {
|
||||||
axios.delete(`${process.env.REACT_APP_API_URL}/boxes/${id}`, {
|
try {
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
await deleteBox(() =>
|
||||||
}).then(() => {
|
api.boxes.delete(token, id)
|
||||||
|
);
|
||||||
setBoxes(boxes.filter(box => box.ID !== id));
|
setBoxes(boxes.filter(box => box.ID !== id));
|
||||||
});
|
} catch (err) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container>
|
<Container>
|
||||||
|
{(boxesError || createError || deleteError) && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
{boxesError?.message || createError?.message || deleteError?.message}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
<TableContainer>
|
{loadingBoxes ? (
|
||||||
<Table size="small">
|
<CircularProgress />
|
||||||
<TableHead>
|
) : (
|
||||||
<TableRow>
|
<TableContainer>
|
||||||
<TableCell>Box Name</TableCell>
|
<Table size="small">
|
||||||
<TableCell>Actions</TableCell>
|
<TableHead>
|
||||||
</TableRow>
|
<TableRow>
|
||||||
</TableHead>
|
<TableCell width="48px"></TableCell>
|
||||||
<TableBody>
|
<TableCell>Box Name</TableCell>
|
||||||
{boxes.map((box) => (
|
<TableCell align="right">Actions</TableCell>
|
||||||
<TableRow key={box.ID}>
|
|
||||||
<TableCell>
|
|
||||||
<RouterLink to={`/boxes/${box.ID}/items`} state={{ boxName: box.name, boxID: box.ID }}>
|
|
||||||
{box.name}
|
|
||||||
</RouterLink>
|
|
||||||
</TableCell>
|
|
||||||
<TableCell>
|
|
||||||
<Button onClick={() => handleDeleteBox(box.ID)} startIcon={<DeleteIcon />}>
|
|
||||||
Delete
|
|
||||||
</Button>
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
</TableHead>
|
||||||
</TableBody>
|
<TableBody>
|
||||||
</Table>
|
{boxes.map((box) => (
|
||||||
</TableContainer>
|
<TableRow key={box.ID}>
|
||||||
<TextField
|
<TableCell>
|
||||||
label="New Box"
|
<Avatar
|
||||||
variant="outlined"
|
sx={{
|
||||||
fullWidth
|
bgcolor: PRIMARY_COLOR,
|
||||||
value={newBoxName}
|
width: 32,
|
||||||
onChange={(e) => setNewBoxName(e.target.value)}
|
height: 32
|
||||||
/>
|
}}
|
||||||
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={handleCreateBox}>
|
>
|
||||||
Add Box
|
<InventoryIcon sx={{ color: SECONDARY_COLOR, fontSize: 20 }} />
|
||||||
</Button>
|
</Avatar>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Box
|
||||||
|
component={RouterLink}
|
||||||
|
to={`/api/v1/boxes/${box.ID}/items`}
|
||||||
|
state={{ boxName: box.name, boxID: box.ID }}
|
||||||
|
sx={{
|
||||||
|
textDecoration: 'none',
|
||||||
|
color: 'inherit',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
'&:hover': {
|
||||||
|
textDecoration: 'underline'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{box.name}
|
||||||
|
</Box>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell align="right">
|
||||||
|
<Button
|
||||||
|
onClick={() => handleDeleteBox(box.ID)}
|
||||||
|
startIcon={<DeleteIcon />}
|
||||||
|
disabled={deletingBox}
|
||||||
|
color="error"
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
{deletingBox ? <CircularProgress size={20} /> : 'Delete'}
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box sx={{ mt: 2 }}>
|
||||||
|
<TextField
|
||||||
|
label="New Box"
|
||||||
|
variant="outlined"
|
||||||
|
fullWidth
|
||||||
|
value={newBoxName}
|
||||||
|
onChange={(e) => setNewBoxName(e.target.value)}
|
||||||
|
disabled={creatingBox}
|
||||||
|
sx={{ mb: 1 }}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
sx={{
|
||||||
|
backgroundColor: PRIMARY_COLOR,
|
||||||
|
borderBottom: '1px solid',
|
||||||
|
borderColor: '#444',
|
||||||
|
color: SECONDARY_COLOR
|
||||||
|
}}
|
||||||
|
variant="contained"
|
||||||
|
onClick={handleCreateBox}
|
||||||
|
disabled={creatingBox || !newBoxName.trim()}
|
||||||
|
fullWidth
|
||||||
|
>
|
||||||
|
{creatingBox ? <CircularProgress size={24} /> : 'Add Box'}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
import React from 'react';
|
||||||
|
import { Alert, Button, Container } from '@mui/material';
|
||||||
|
|
||||||
|
class ErrorBoundary extends React.Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
this.state = { hasError: false, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error) {
|
||||||
|
return { hasError: true, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
return (
|
||||||
|
<Container>
|
||||||
|
<Alert severity="error" sx={{ mt: 2 }}>
|
||||||
|
Something went wrong
|
||||||
|
<Button
|
||||||
|
onClick={() => window.location.reload()}
|
||||||
|
variant="outlined"
|
||||||
|
size="small"
|
||||||
|
sx={{ ml: 2 }}
|
||||||
|
>
|
||||||
|
Reload Page
|
||||||
|
</Button>
|
||||||
|
</Alert>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.props.children;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ErrorBoundary;
|
|
@ -1,280 +1,230 @@
|
||||||
// src/components/ItemDetails.js
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
import {
|
||||||
import { TextField, Button, Container, Avatar, Tooltip } from '@mui/material';
|
TextField,
|
||||||
import axios from 'axios';
|
Button,
|
||||||
|
Container,
|
||||||
|
Avatar,
|
||||||
|
Tooltip,
|
||||||
|
Alert,
|
||||||
|
CircularProgress,
|
||||||
|
Box,
|
||||||
|
Typography
|
||||||
|
} from '@mui/material';
|
||||||
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
||||||
//import { useNavigate } from 'react-router-dom'; // Import useNavigate
|
import { useApiCall } from './hooks/useApiCall';
|
||||||
|
import { api } from '../services/api';
|
||||||
|
import TagManager from './tagManager';
|
||||||
|
|
||||||
export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
|
export default function ItemDetails({ item: initialItem, token, onSave, onClose }) {
|
||||||
const [name, setName] = useState(item.name);
|
const [item, setItem] = useState(initialItem);
|
||||||
const [description, setDescription] = useState(item.description);
|
const [name, setName] = useState(initialItem.name);
|
||||||
const [imagePath, setImagePath] = useState(item.image_path || '');
|
const [description, setDescription] = useState(initialItem.description);
|
||||||
const [imageSrc, setImageSrc] = useState('/images/default.jpg'); // Initial default image
|
const [imagePath, setImagePath] = useState(initialItem.image_path || '');
|
||||||
const fileInputRef = useRef(null); // Add this line to define fileInputRef
|
const [imageSrc, setImageSrc] = useState('/images/default.jpg');
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
const fileInputRef = useRef(null);
|
||||||
const [imageOverlayVisible, setImageOverlayVisible] = useState(false);
|
const [imageOverlayVisible, setImageOverlayVisible] = useState(false);
|
||||||
// const navigate = useNavigate(); // Initialize useNavigate
|
|
||||||
// eslint says boxName is defined but never used, but when I remove it it fails to compile
|
|
||||||
// because boxName is undefined
|
|
||||||
// eslint-disable-next-line
|
|
||||||
const [boxName, setBoxName] = useState('');
|
|
||||||
const [boxes, setBoxes] = useState([]);
|
const [boxes, setBoxes] = useState([]);
|
||||||
const [selectedBoxId, setSelectedBoxId] = useState(item.box_id);
|
const [selectedBoxId, setSelectedBoxId] = useState(initialItem.box_id);
|
||||||
|
|
||||||
//console.log("item.box_id: " + item.box_id);
|
const { execute: fetchBoxes, loading: loadingBoxes, error: boxesError } = useApiCall();
|
||||||
|
const { execute: fetchItem, loading: loadingItem } = useApiCall();
|
||||||
|
const { execute: updateItem, loading: savingItem, error: saveError } = useApiCall();
|
||||||
|
const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall();
|
||||||
|
|
||||||
|
// Single effect to load initial data
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchBoxes = async () => {
|
const loadInitialData = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await axios.get(`${process.env.REACT_APP_API_URL}/boxes`, {
|
// Fetch item and boxes in parallel
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
const [itemResponse, boxesResponse] = await Promise.all([
|
||||||
});
|
fetchItem(() => api.items.getOne(token, initialItem.ID)),
|
||||||
setBoxes(response.data);
|
fetchBoxes(() => api.boxes.getAll(token))
|
||||||
} catch (error) {
|
]);
|
||||||
console.error('Error fetching boxes:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
fetchBoxes();
|
|
||||||
}, [token]);
|
|
||||||
|
|
||||||
|
const updatedItem = itemResponse.data;
|
||||||
|
setItem(updatedItem);
|
||||||
|
setName(updatedItem.name);
|
||||||
|
setDescription(updatedItem.description);
|
||||||
|
setImagePath(updatedItem.image_path || '');
|
||||||
|
setBoxes(boxesResponse.data);
|
||||||
|
|
||||||
const handleBoxChange = (event) => {
|
// Load image
|
||||||
const newBoxId = event.target.value;
|
try {
|
||||||
setSelectedBoxId(newBoxId); // Update only this state
|
const imageResponse = await api.items.getImage(token, initialItem.ID);
|
||||||
//console.log('Selected box ID:', newBoxId);
|
const reader = new FileReader();
|
||||||
};
|
reader.onload = () => {
|
||||||
|
setImageSrc(reader.result);
|
||||||
useEffect(() => {
|
setLoading(false);
|
||||||
// Fetch box details only when the selectedBoxId changes
|
|
||||||
const getBoxDetails = async (boxId) => {
|
|
||||||
try {
|
|
||||||
const boxIdNumber = +boxId;
|
|
||||||
if (isNaN(boxIdNumber)) {
|
|
||||||
console.error('Invalid boxId:', boxId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const response = await axios.get(`${process.env.REACT_APP_API_URL}/boxes/${boxIdNumber}`, {
|
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
|
||||||
});
|
|
||||||
setBoxName(response.data.name);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching box details:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (selectedBoxId !== item.box_id) {
|
|
||||||
getBoxDetails(selectedBoxId); // Fetch when selected box changes
|
|
||||||
//console.log("selectedBoxId:", selectedBoxId);
|
|
||||||
} else if (item.box_id) {
|
|
||||||
getBoxDetails(item.box_id); // Fetch when boxId exists and selectedBoxId is empty
|
|
||||||
//console.log("item.box_id:", item.box_id);
|
|
||||||
}
|
|
||||||
}, [selectedBoxId, token, item.box_id]); // Removed `boxId` from dependencies
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
// Function to fetch image similar to getImageSrc in Items.js
|
|
||||||
const getImageSrc = (itemId) => {
|
|
||||||
return axios.get(`${process.env.REACT_APP_API_URL}/items/${itemId}/image`, {
|
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
|
||||||
responseType: 'blob'
|
|
||||||
})
|
|
||||||
.then(response => {
|
|
||||||
if (response.status === 200) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = () => resolve(reader.result);
|
|
||||||
reader.onerror = reject;
|
|
||||||
reader.readAsDataURL(response.data);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
throw new Error('Image fetch failed');
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
// Return the data URL of the default image if image fetch fails
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const img = new Image();
|
|
||||||
img.src = '/default.jpg';
|
|
||||||
img.onload = () => {
|
|
||||||
const canvas = document.createElement('canvas');
|
|
||||||
canvas.width = img.width;
|
|
||||||
canvas.height = img.height;
|
|
||||||
const ctx = canvas.getContext('2d');
|
|
||||||
ctx.drawImage(img, 0, 0);
|
|
||||||
const dataURL = canvas.toDataURL();
|
|
||||||
resolve(dataURL);
|
|
||||||
};
|
};
|
||||||
img.onerror = reject;
|
reader.readAsDataURL(imageResponse.data);
|
||||||
});
|
} catch (err) {
|
||||||
});
|
setImageSrc('/default.jpg');
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fetch the image when the component mounts or the item changes
|
loadInitialData();
|
||||||
getImageSrc(item.ID).then(dataUrl => setImageSrc(dataUrl));
|
}, []); // Empty dependency array - only run once on mount
|
||||||
}, [item.ID, token]);
|
|
||||||
|
|
||||||
// const handleCloseItemDetails = () => {
|
const handleImageUpload = async () => {
|
||||||
// onClose(); // Call the onClose prop to close the modal
|
if (!fileInputRef.current?.files?.[0]) return null;
|
||||||
// navigate(`/boxes/${boxId}/items`); // Navigate back to the items list
|
|
||||||
// };
|
|
||||||
|
|
||||||
const handleImageUpload = useCallback(async () => {
|
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('image', fileInputRef.current.files[0]);
|
formData.append('image', fileInputRef.current.files[0]);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await axios.post(`${process.env.REACT_APP_API_URL}/items/${item.ID}/upload`, formData, {
|
const response = await uploadImage(() =>
|
||||||
headers: {
|
api.items.uploadImage(token, item.ID, formData)
|
||||||
Authorization: `Bearer ${token}`,
|
);
|
||||||
'Content-Type': 'multipart/form-data'
|
return response.data.imagePath;
|
||||||
}
|
} catch (err) {
|
||||||
});
|
return null;
|
||||||
// Handle successful upload (e.g., show a success message)
|
|
||||||
//console.log('Image uploaded successfully!', response.data.imagePath);
|
|
||||||
return response.data.imagePath; // Indicate successful upload
|
|
||||||
} catch (error) {
|
|
||||||
// Handle upload error (e.g., show an error message)
|
|
||||||
console.error('Image upload failed:', error);
|
|
||||||
}
|
|
||||||
}, [item.ID, token]);
|
|
||||||
|
|
||||||
// eslint-disable-next-line
|
|
||||||
const updateItemBoxId = async () => {
|
|
||||||
try {
|
|
||||||
// eslint-disable-next-line
|
|
||||||
const response = await axios.put(`${process.env.REACT_APP_API_URL}/items/${item.id}`, {
|
|
||||||
box_id: selectedBoxId,
|
|
||||||
}, {
|
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
|
||||||
});
|
|
||||||
// Update the item's boxId
|
|
||||||
item.box_id = selectedBoxId;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error updating item boxId:', error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSave = useCallback( async () => {
|
const handleSave = async () => {
|
||||||
let imagePath;
|
if (fileInputRef.current?.files?.[0]) {
|
||||||
// 1. Handle image upload first if a new image is selected
|
await handleImageUpload();
|
||||||
if (fileInputRef.current.files[0]) {
|
|
||||||
// eslint-disable-next-line
|
|
||||||
imagePath = await handleImageUpload();
|
|
||||||
}
|
}
|
||||||
//console.log("Selected box ID:", selectedBoxId)
|
|
||||||
|
|
||||||
// 2. Update item details (name, description, etc.)
|
|
||||||
try {
|
try {
|
||||||
await axios.put(`${process.env.REACT_APP_API_URL}/items/${item.ID}`, {
|
await updateItem(() => api.items.update(token, item.ID, {
|
||||||
name,
|
name,
|
||||||
description,
|
description,
|
||||||
box_id: +selectedBoxId, // Ensure the updated selected box is saved
|
box_id: +selectedBoxId,
|
||||||
}, {
|
}));
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
onSave();
|
||||||
});
|
} catch (err) {}
|
||||||
onSave(); // Notify parent to refresh items
|
|
||||||
} catch (error) {
|
|
||||||
// Handle update error
|
|
||||||
console.error('Item update failed:', error);
|
|
||||||
}
|
|
||||||
}, [item.ID, name, description, selectedBoxId, token, onSave, handleImageUpload]);
|
|
||||||
|
|
||||||
const handleImageError = (e) => {
|
|
||||||
e.target.src = '/images/default.jpg'; // Fallback to default image on error
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAvatarClick = () => {
|
const handleBoxChange = (event) => {
|
||||||
setImageOverlayVisible(true);
|
setSelectedBoxId(event.target.value);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCloseOverlay = () => {
|
const handleTagsChange = (newTags) => {
|
||||||
setImageOverlayVisible(false);
|
setItem(prev => ({...prev, tags: newTags}));
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container>
|
<Container>
|
||||||
<h3>Edit Item: {item.name}</h3>
|
<h3>Edit Item: {name}</h3>
|
||||||
|
|
||||||
{/* Display the item image as an avatar */}
|
{(error || boxesError || saveError || uploadError) && (
|
||||||
<Tooltip title="Click to enlarge">
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
<Avatar
|
{error?.message || boxesError?.message || saveError?.message || uploadError?.message}
|
||||||
src={imageSrc}
|
</Alert>
|
||||||
alt={name}
|
|
||||||
onError={handleImageError}
|
|
||||||
sx={{ width: 200, height: 200, marginBottom: '16px' }} // Style the Avatar
|
|
||||||
onClick={handleAvatarClick}
|
|
||||||
/>
|
|
||||||
</Tooltip>
|
|
||||||
{imageOverlayVisible && (
|
|
||||||
<div className="image-overlay">
|
|
||||||
<img src={imageSrc} alt={name} />
|
|
||||||
<button className="close-button" onClick={handleCloseOverlay}>
|
|
||||||
Close
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
<TextField
|
|
||||||
label="Item Name"
|
|
||||||
variant="outlined"
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
value={name}
|
|
||||||
onChange={(e) => setName(e.target.value)}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
label="Item Description"
|
|
||||||
variant="outlined"
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
value={description}
|
|
||||||
onChange={(e) => setDescription(e.target.value)}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
label="Item Image Path"
|
|
||||||
variant="outlined"
|
|
||||||
fullWidth
|
|
||||||
margin="normal"
|
|
||||||
value={imagePath}
|
|
||||||
onChange={(e) => setImagePath(e.target.value)}
|
|
||||||
sx={{ display: 'none' }}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept="image/*"
|
|
||||||
ref={fileInputRef}
|
|
||||||
style={{ display: 'none' }}
|
|
||||||
id="editItemImageUpload" // Unique ID
|
|
||||||
/>
|
|
||||||
<select value={selectedBoxId} onChange={handleBoxChange}>
|
|
||||||
<option value="">No box</option>
|
|
||||||
{boxes.map((box) => (
|
|
||||||
// eslint-disable-next-line
|
|
||||||
//console.log('Box at the selection point:', box.ID),
|
|
||||||
//console.log("Box name:", box.name),
|
|
||||||
<option key={box.ID} value={box.ID}>
|
|
||||||
{box.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<br/>
|
|
||||||
<br/>
|
|
||||||
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" component="label" htmlFor="editItemImageUpload">
|
|
||||||
Upload Image
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept="image/*"
|
|
||||||
id="image-upload"
|
|
||||||
style={{ display: 'none' }}
|
|
||||||
onChange={(e) => {
|
|
||||||
// You can handle image preview here if needed
|
|
||||||
setImagePath(e.target.files[0].name);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={handleSave}>
|
{loading ? (
|
||||||
Save Changes
|
<CircularProgress />
|
||||||
</Button>
|
) : (
|
||||||
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" onClick={onClose}>Close</Button>
|
/* Rest of your JSX remains the same */
|
||||||
|
// ... existing JSX code ...
|
||||||
|
<Box>
|
||||||
|
{/* Image section */}
|
||||||
|
<Tooltip title="Click to enlarge">
|
||||||
|
<Avatar
|
||||||
|
src={imageSrc}
|
||||||
|
alt={name}
|
||||||
|
sx={{ width: 200, height: 200, marginBottom: '16px' }}
|
||||||
|
onClick={() => setImageOverlayVisible(true)}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
{/* Form fields */}
|
||||||
|
<TextField
|
||||||
|
label="Item Name"
|
||||||
|
variant="outlined"
|
||||||
|
fullWidth
|
||||||
|
margin="normal"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
disabled={savingItem}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
label="Item Description"
|
||||||
|
variant="outlined"
|
||||||
|
fullWidth
|
||||||
|
margin="normal"
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
disabled={savingItem}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Box selection */}
|
||||||
|
{loadingBoxes ? (
|
||||||
|
<CircularProgress size={24} />
|
||||||
|
) : (
|
||||||
|
<select
|
||||||
|
value={selectedBoxId}
|
||||||
|
onChange={handleBoxChange}
|
||||||
|
disabled={savingItem}
|
||||||
|
>
|
||||||
|
<option value="">No box</option>
|
||||||
|
{boxes.map((box) => (
|
||||||
|
<option key={box.ID} value={box.ID}>
|
||||||
|
{box.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tags section */}
|
||||||
|
<Box sx={{ my: 2 }}>
|
||||||
|
<Typography variant="subtitle1" gutterBottom>Tags</Typography>
|
||||||
|
<TagManager
|
||||||
|
token={token}
|
||||||
|
itemId={item.ID}
|
||||||
|
initialTags={item.tags || []}
|
||||||
|
onTagsChange={handleTagsChange}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Buttons */}
|
||||||
|
<Box sx={{ mt: 2 }}>
|
||||||
|
<Button
|
||||||
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR, mr: 1 }}
|
||||||
|
variant="contained"
|
||||||
|
component="label"
|
||||||
|
disabled={uploadingImage || savingItem}
|
||||||
|
>
|
||||||
|
{uploadingImage ? <CircularProgress size={24} /> : 'Upload Image'}
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept="image/*"
|
||||||
|
ref={fileInputRef}
|
||||||
|
style={{ display: 'none' }}
|
||||||
|
onChange={(e) => setImagePath(e.target.files[0]?.name || '')}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR, mr: 1 }}
|
||||||
|
variant="contained"
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={savingItem}
|
||||||
|
>
|
||||||
|
{savingItem ? <CircularProgress size={24} /> : 'Save Changes'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
||||||
|
variant="contained"
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={savingItem}
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
|
@ -1,19 +1,9 @@
|
||||||
import React, { useEffect, useState, useCallback, useRef } from 'react';
|
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
|
||||||
import {
|
import {
|
||||||
Container,
|
Container,
|
||||||
List,
|
|
||||||
ListItem,
|
|
||||||
ListItemText,
|
|
||||||
TextField,
|
|
||||||
Button,
|
Button,
|
||||||
IconButton,
|
IconButton,
|
||||||
Typography,
|
TextField,
|
||||||
Avatar,
|
|
||||||
ListItemAvatar,
|
|
||||||
Dialog,
|
|
||||||
DialogTitle,
|
|
||||||
DialogContent,
|
|
||||||
DialogActions,
|
|
||||||
TableContainer,
|
TableContainer,
|
||||||
Table,
|
Table,
|
||||||
TableHead,
|
TableHead,
|
||||||
|
@ -21,327 +11,299 @@ import {
|
||||||
TableCell,
|
TableCell,
|
||||||
TableBody,
|
TableBody,
|
||||||
Box,
|
Box,
|
||||||
Tooltip
|
Tooltip,
|
||||||
|
Avatar,
|
||||||
|
Dialog,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContent,
|
||||||
|
DialogActions,
|
||||||
|
Alert,
|
||||||
|
CircularProgress,
|
||||||
|
Chip,
|
||||||
|
Typography,
|
||||||
|
FormGroup
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
|
|
||||||
import { Delete as DeleteIcon, Edit as EditIcon } from '@mui/icons-material';
|
import { Delete as DeleteIcon, Edit as EditIcon } from '@mui/icons-material';
|
||||||
import axios from 'axios';
|
import { useParams, useLocation } from 'react-router-dom';
|
||||||
import { useParams, useLocation } from 'react-router-dom';
|
|
||||||
import ItemDetails from './ItemDetails';
|
|
||||||
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
||||||
|
import { useApiCall } from './hooks/useApiCall';
|
||||||
|
import { api } from '../services/api';
|
||||||
|
import ItemDetails from './ItemDetails';
|
||||||
|
import TagManager from './tagManager';
|
||||||
|
|
||||||
|
const Item = React.memo(({ item, onDelete, onEdit, itemImages }) => (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>
|
||||||
|
<Avatar src={itemImages[item.ID] || '/images/default.jpg'} />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{item.name}</TableCell>
|
||||||
|
<TableCell>{item.description}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{item.tags?.map(tag => (
|
||||||
|
<Chip
|
||||||
|
key={tag.ID}
|
||||||
|
label={tag.name}
|
||||||
|
size="small"
|
||||||
|
style={{
|
||||||
|
backgroundColor: tag.color,
|
||||||
|
color: '#fff',
|
||||||
|
margin: '0 2px'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Box display="flex" justifyContent="space-between" width="100%">
|
||||||
|
<Tooltip title="Edit Item">
|
||||||
|
<IconButton onClick={() => onEdit(item)} size="large" sx={{ mr: 1 }}>
|
||||||
|
<EditIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="Delete Item">
|
||||||
|
<IconButton onClick={() => onDelete(item.ID)} size="large" color="error">
|
||||||
|
<DeleteIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</Box>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
));
|
||||||
|
|
||||||
export default function Items({ token }) {
|
export default function Items({ token }) {
|
||||||
const { id: boxId } = useParams();
|
const { id: boxId } = useParams();
|
||||||
const [items, setItems] = useState([]);
|
const [items, setItems] = useState([]);
|
||||||
const [newItemName, setNewItemName] = useState('');
|
const [newItemName, setNewItemName] = useState('');
|
||||||
const [newItemDescription, setNewItemDescription] = useState('');
|
const [newItemDescription, setNewItemDescription] = useState('');
|
||||||
// const [newItemImagePath, setNewItemImagePath] = useState('/images/default.jpg');
|
|
||||||
const [editingItem, setEditingItem] = useState(null);
|
const [editingItem, setEditingItem] = useState(null);
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const boxName = location.state?.boxName || 'Unknown Box';
|
const boxName = location.state?.boxName || 'All Boxes';
|
||||||
// const boxID = location.state?.boxId; // used in handleClose function
|
|
||||||
const [itemImages, setItemImages] = useState({});
|
const [itemImages, setItemImages] = useState({});
|
||||||
const fileInputRef = useRef(null);
|
const fileInputRef = useRef(null);
|
||||||
const [openAddItemDialog, setOpenAddItemDialog] = useState(false); // For Add Item dialog
|
const [openAddItemDialog, setOpenAddItemDialog] = useState(false);
|
||||||
const { id } = useParams();
|
|
||||||
const boxID = id;
|
|
||||||
const url = boxId === undefined ? `${process.env.REACT_APP_API_URL}/items` : `${process.env.REACT_APP_API_URL}/boxes/${boxId}/items`;
|
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [availableTags, setAvailableTags] = useState([]);
|
||||||
|
const [selectedTags, setSelectedTags] = useState([]);
|
||||||
|
|
||||||
|
const { execute: fetchItems, loading: loadingItems, error: itemsError } = useApiCall();
|
||||||
|
const { execute: fetchTags, loading: loadingTags, error: tagsError } = useApiCall();
|
||||||
|
const { execute: createItem, loading: creatingItem, error: createError } = useApiCall();
|
||||||
|
const { execute: deleteItem, loading: deletingItem, error: deleteError } = useApiCall();
|
||||||
|
const { execute: uploadImage, loading: uploadingImage, error: uploadError } = useApiCall();
|
||||||
|
|
||||||
const debugLog = (message) => {
|
// Fetch items and tags on component mount
|
||||||
if (process.env.DEBUG_API) {
|
useEffect(() => {
|
||||||
console.log(message);
|
const loadData = async () => {
|
||||||
}
|
try {
|
||||||
|
// Fetch items and tags in parallel
|
||||||
|
const [itemsResponse, tagsResponse] = await Promise.all([
|
||||||
|
fetchItems(() => boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)),
|
||||||
|
fetchTags(() => api.tags.getAll(token))
|
||||||
|
]);
|
||||||
|
|
||||||
|
setItems(itemsResponse.data);
|
||||||
|
setAvailableTags(tagsResponse.data);
|
||||||
|
|
||||||
|
// Fetch images for each item
|
||||||
|
itemsResponse.data.forEach(item => {
|
||||||
|
api.items.getImage(token, item.ID)
|
||||||
|
.then(response => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => {
|
||||||
|
setItemImages(prev => ({
|
||||||
|
...prev,
|
||||||
|
[item.ID]: reader.result
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(response.data);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setItemImages(prev => ({
|
||||||
|
...prev,
|
||||||
|
[item.ID]: '/default.jpg'
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (err) {}
|
||||||
|
};
|
||||||
|
loadData();
|
||||||
|
}, [token, boxId]);
|
||||||
|
|
||||||
|
// Filter items based on search query and selected tags
|
||||||
|
const filteredItems = useMemo(() => {
|
||||||
|
return items.filter(item => {
|
||||||
|
// Text search match
|
||||||
|
const textMatch =
|
||||||
|
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
item.description.toLowerCase().includes(searchQuery.toLowerCase());
|
||||||
|
|
||||||
|
// Tag match - if no tags selected, show all items
|
||||||
|
const tagMatch = selectedTags.length === 0 ||
|
||||||
|
selectedTags.every(tagId =>
|
||||||
|
item.tags?.some(itemTag => itemTag.ID === tagId)
|
||||||
|
);
|
||||||
|
|
||||||
|
return textMatch && tagMatch;
|
||||||
|
});
|
||||||
|
}, [items, searchQuery, selectedTags]);
|
||||||
|
|
||||||
|
// Handle tag selection
|
||||||
|
const handleTagSelect = (tagId) => {
|
||||||
|
setSelectedTags(prev =>
|
||||||
|
prev.includes(tagId)
|
||||||
|
? prev.filter(id => id !== tagId)
|
||||||
|
: [...prev, tagId]
|
||||||
|
);
|
||||||
};
|
};
|
||||||
debugLog("Box ID: " + boxID);
|
|
||||||
|
|
||||||
// const handleSelectItem = (item) => {
|
// Rest of the component remains the same...
|
||||||
// setSelectedItem(item);
|
// (keeping all existing functions like handleAddItem, handleDeleteItem, etc.)
|
||||||
// };
|
const handleAddItem = useCallback(() => {
|
||||||
const handleAddItem = () => {
|
|
||||||
setOpenAddItemDialog(true);
|
setOpenAddItemDialog(true);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const handleCloseAddItemDialog = () => {
|
const handleCloseAddItemDialog = useCallback(() => {
|
||||||
setOpenAddItemDialog(false);
|
setOpenAddItemDialog(false);
|
||||||
setNewItemName('');
|
setNewItemName('');
|
||||||
setNewItemDescription('');
|
setNewItemDescription('');
|
||||||
// setNewItemImagePath('');
|
|
||||||
if (fileInputRef.current) {
|
if (fileInputRef.current) {
|
||||||
fileInputRef.current.value = '';
|
fileInputRef.current.value = '';
|
||||||
}
|
}
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
/**
|
const generateUniqueImageName = useCallback((imageName) => {
|
||||||
* This function takes an image name and returns a unique image name.
|
|
||||||
* The purpose of this function is to prevent overwriting of images with the same name.
|
|
||||||
* If the image name is 'image.jpg', a random string is generated and appended to the image name.
|
|
||||||
* This is used to prevent overwriting of images with the same name.
|
|
||||||
* For example, if an image named 'image.jpg' is uploaded, the function will return 'image_8xgu6hcu.jpg'
|
|
||||||
* This ensures that the image will not overwrite any existing image with the same name.
|
|
||||||
* @param {string} imageName - The name of the image
|
|
||||||
* @return {string} - The unique image name
|
|
||||||
*/
|
|
||||||
const generateUniqueImageName = (imageName) => {
|
|
||||||
if (imageName.toLowerCase() === 'image.jpg') {
|
if (imageName.toLowerCase() === 'image.jpg') {
|
||||||
// Generate a random string
|
|
||||||
const randomString = Math.random().toString(36).substr(2, 9);
|
const randomString = Math.random().toString(36).substr(2, 9);
|
||||||
// Append the random string to the image name
|
|
||||||
return `image_${randomString}.jpg`;
|
return `image_${randomString}.jpg`;
|
||||||
}
|
}
|
||||||
// Return the original image name if it's not 'image.jpg'
|
|
||||||
return imageName;
|
return imageName;
|
||||||
};
|
}, []);
|
||||||
|
const handleDeleteItem = useCallback(async (itemId) => {
|
||||||
|
|
||||||
const handleImageUpload = async (itemId, imageFile, newImageName) => {
|
|
||||||
const formData = new FormData();
|
|
||||||
//const imageFile = fileInputRef.current.files[0];
|
|
||||||
//const newImageName = generateUniqueImageName(imageFile.name);
|
|
||||||
formData.append('image', new File([imageFile], newImageName, {
|
|
||||||
type: imageFile.type,
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Create a new file with the unique name
|
|
||||||
// eslint-disable-next-line
|
|
||||||
const newImageFile = new File([imageFile], newImageName, {
|
|
||||||
type: imageFile.type,
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await axios.post(`${process.env.REACT_APP_API_URL}/items/${itemId}/upload`, formData, {
|
await deleteItem(() => api.items.delete(token, itemId));
|
||||||
headers: {
|
setItems(prev => prev.filter(item => item.ID !== itemId));
|
||||||
Authorization: `Bearer ${token}`,
|
} catch (err) {}
|
||||||
'Content-Type': 'multipart/form-data'
|
}, [token, deleteItem]);
|
||||||
}
|
|
||||||
});
|
|
||||||
// console.log('Image uploaded successfully!');
|
|
||||||
return response.data.imagePath; // Indicate successful upload
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Image upload failed:', error);
|
|
||||||
return null; // Indicate upload failure
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
const handleEditItem = useCallback((item) => {
|
||||||
* Handle saving a new item.
|
|
||||||
*
|
|
||||||
* This function first creates the item without the image, then if the item creation is successful,
|
|
||||||
* it uploads the image associated with the item.
|
|
||||||
*
|
|
||||||
* @return {Promise<void>}
|
|
||||||
*/
|
|
||||||
const handleSaveNewItem = async () => {
|
|
||||||
try {
|
|
||||||
// Step 1: Create the item first
|
|
||||||
// This sends a request to the API to create a new item with the
|
|
||||||
// name and description provided. The box_id is set to the selected
|
|
||||||
// box ID.
|
|
||||||
const newItemResponse = await axios.post(`${process.env.REACT_APP_API_URL}/items`, {
|
|
||||||
name: newItemName,
|
|
||||||
description: newItemDescription,
|
|
||||||
box_id: parseInt(boxId, 10) // Ensure boxId is converted to an integer
|
|
||||||
}, {
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('New item created:', newItemResponse.status);
|
|
||||||
|
|
||||||
// Step 2: If item creation is successful, upload the image
|
|
||||||
if (newItemResponse.status === 200 && fileInputRef.current.files[0]) {
|
|
||||||
// Get the ID of the newly created item
|
|
||||||
const newItemId = newItemResponse.data.id;
|
|
||||||
|
|
||||||
// Get the image file that was uploaded
|
|
||||||
const imageFile = fileInputRef.current.files[0];
|
|
||||||
|
|
||||||
// Generate a unique image name by appending a random string
|
|
||||||
// to the image file name. This is used to prevent overwriting
|
|
||||||
// of images with the same name.
|
|
||||||
const newImageName = generateUniqueImageName(imageFile.name);
|
|
||||||
|
|
||||||
// Upload the image file with the unique name to the server
|
|
||||||
const uploadedImagePath = await handleImageUpload(newItemId, fileInputRef.current.files[0], newImageName);
|
|
||||||
|
|
||||||
if (uploadedImagePath) {
|
|
||||||
// The image was uploaded successfully. Log the uploaded image path
|
|
||||||
console.log("Image path to save:", uploadedImagePath);
|
|
||||||
|
|
||||||
// You might want to update your item in the backend with the image path
|
|
||||||
// For example:
|
|
||||||
// await axios.put(...);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
// The image upload failed. Log an error message
|
|
||||||
console.error('Failed to upload image for the new item.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close the add item dialog
|
|
||||||
handleCloseAddItemDialog();
|
|
||||||
|
|
||||||
// Fetch the items again to get the latest data
|
|
||||||
fetchItems();
|
|
||||||
} catch (error) {
|
|
||||||
// Catch any errors that may occur during the item creation
|
|
||||||
// and image upload process. Log the error message
|
|
||||||
console.error('Error adding item:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//const [selectedItem, setSelectedItem] = React.useState(null);
|
|
||||||
|
|
||||||
const handleCloseItemDetails = () => {
|
|
||||||
setEditingItem(null); // Close the ItemDetails modal
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleImageError = (e) => {
|
|
||||||
if (e.target.src.startsWith('data:image/')) {
|
|
||||||
console.error("Default image failed to load. Check the file path.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = () => {
|
|
||||||
e.target.onerror = null;
|
|
||||||
e.target.src = reader.result;
|
|
||||||
};
|
|
||||||
fetch('/default.jpg')
|
|
||||||
.then(res => res.blob())
|
|
||||||
.then(blob => reader.readAsDataURL(blob))
|
|
||||||
.catch(error => console.error("Error loading default image:", error));
|
|
||||||
};
|
|
||||||
|
|
||||||
const getImageSrc = useCallback((itemId) => {
|
|
||||||
return axios.get(`${process.env.REACT_APP_API_URL}/items/${itemId}/image`, {
|
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
|
||||||
responseType: 'blob'
|
|
||||||
})
|
|
||||||
.then(response => {
|
|
||||||
if (response.status === 200) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = () => resolve(reader.result);
|
|
||||||
reader.onerror = reject;
|
|
||||||
reader.readAsDataURL(response.data);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
throw new Error('Image fetch failed');
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const img = new Image();
|
|
||||||
img.src = '/default.jpg';
|
|
||||||
img.onload = () => {
|
|
||||||
const canvas = document.createElement('canvas');
|
|
||||||
canvas.width = img.width;
|
|
||||||
canvas.height = img.height;
|
|
||||||
const ctx = canvas.getContext('2d');
|
|
||||||
ctx.drawImage(img, 0, 0);
|
|
||||||
resolve(canvas.toDataURL());
|
|
||||||
};
|
|
||||||
img.onerror = reject;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}, [token]);
|
|
||||||
|
|
||||||
const fetchItems = useCallback(() => {
|
|
||||||
axios.get( url, {
|
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
|
||||||
}).then(response => {
|
|
||||||
setItems(response.data);
|
|
||||||
|
|
||||||
// Fetch images for each item
|
|
||||||
response.data.forEach(item => {
|
|
||||||
getImageSrc(item.ID).then(imageDataUrl => {
|
|
||||||
setItemImages(prevItemImages => ({
|
|
||||||
...prevItemImages,
|
|
||||||
[item.ID]: imageDataUrl
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}, [token, getImageSrc, url]);
|
|
||||||
// lint says I don't need boxId here
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchItems();
|
|
||||||
}, [boxId, token, fetchItems]);
|
|
||||||
|
|
||||||
// const handleAddItem = () => {
|
|
||||||
// const formData = new FormData();
|
|
||||||
// formData.append('name', newItemName);
|
|
||||||
// formData.append('description', newItemDescription);
|
|
||||||
// formData.append('box_id', parseInt(boxId, 10));
|
|
||||||
// // Append image only if a new one is selected
|
|
||||||
// if (fileInputRef.current.files[0]) {
|
|
||||||
// formData.append('image', fileInputRef.current.files[0]);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// axios.post(`${process.env.REACT_APP_API_URL}/items`, formData, {
|
|
||||||
// headers: {
|
|
||||||
// Authorization: `Bearer ${token}`,
|
|
||||||
// 'Content-Type': 'multipart/form-data' // Important for file uploads
|
|
||||||
// }
|
|
||||||
// }).then(() => {
|
|
||||||
// setNewItemName('');
|
|
||||||
// setNewItemDescription('');
|
|
||||||
// setNewItemImagePath('');
|
|
||||||
// // Clear the file input
|
|
||||||
// if (fileInputRef.current) {
|
|
||||||
// fileInputRef.current.value = '';
|
|
||||||
// }
|
|
||||||
// fetchItems();
|
|
||||||
// });
|
|
||||||
// };
|
|
||||||
|
|
||||||
const handleDeleteItem = (itemId) => {
|
|
||||||
axios.delete(`${process.env.REACT_APP_API_URL}/items/${itemId}`, {
|
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
|
||||||
}).then(() => {
|
|
||||||
fetchItems();
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleEditItem = (item) => {
|
|
||||||
setEditingItem(item);
|
setEditingItem(item);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const handleSaveEdit = () => {
|
const handleSaveEdit = useCallback(async () => {
|
||||||
setEditingItem(null);
|
setEditingItem(null);
|
||||||
fetchItems();
|
// Refresh the items list after editing
|
||||||
};
|
try {
|
||||||
|
const response = await fetchItems(() =>
|
||||||
|
boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)
|
||||||
|
);
|
||||||
|
setItems(response.data);
|
||||||
|
} catch (err) {}
|
||||||
|
}, [token, boxId, fetchItems]);
|
||||||
|
|
||||||
|
const handleSaveNewItem = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const newItemResponse = await createItem(() =>
|
||||||
|
api.items.create(token, {
|
||||||
|
name: newItemName,
|
||||||
|
description: newItemDescription,
|
||||||
|
box_id: parseInt(boxId, 10)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
if (newItemResponse.status === 200 && fileInputRef.current?.files?.[0]) {
|
||||||
|
const imageFile = fileInputRef.current.files[0];
|
||||||
|
const newImageName = generateUniqueImageName(imageFile.name);
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('image', new File([imageFile], newImageName, {
|
||||||
|
type: imageFile.type,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await uploadImage(() =>
|
||||||
|
api.items.uploadImage(token, newItemResponse.data.id, formData)
|
||||||
|
);
|
||||||
|
if (newItemResponse.data.id) {
|
||||||
|
try {
|
||||||
|
const imageResponse = await api.items.getImage(token, newItemResponse.data.id);
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => {
|
||||||
|
setItemImages(prev => ({
|
||||||
|
...prev,
|
||||||
|
[newItemResponse.data.id]: reader.result
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(imageResponse.data);
|
||||||
|
} catch (err) {
|
||||||
|
setItemImages(prev => ({
|
||||||
|
...prev,
|
||||||
|
[newItemResponse.data.id]: '/default.jpg'
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleCloseAddItemDialog();
|
||||||
|
|
||||||
|
const response = await fetchItems(() =>
|
||||||
|
boxId ? api.items.getByBox(token, boxId) : api.items.getAll(token)
|
||||||
|
);
|
||||||
|
setItems(response.data);
|
||||||
|
} catch (err) {}
|
||||||
|
}, [token, boxId, newItemName, newItemDescription, createItem, uploadImage, fetchItems, generateUniqueImageName]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container>
|
<Container>
|
||||||
<TextField
|
{(itemsError || tagsError || createError || deleteError || uploadError) && (
|
||||||
label="Search"
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
variant="outlined"
|
{itemsError?.message || tagsError?.message || createError?.message ||
|
||||||
fullWidth
|
deleteError?.message || uploadError?.message}
|
||||||
margin="normal"
|
</Alert>
|
||||||
value={searchQuery}
|
)}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
|
||||||
/>
|
<Box sx={{ mb: 3 }}>
|
||||||
<h2>Items in Box: {boxName === "Unknown Box" ? "All Boxes" : `${boxName} (${items.length} items)`}</h2>
|
<TextField
|
||||||
<input
|
label="Search items..."
|
||||||
type="file"
|
variant="outlined"
|
||||||
accept="image/*"
|
fullWidth
|
||||||
ref={fileInputRef}
|
margin="normal"
|
||||||
style={{ display: 'none' }}
|
value={searchQuery}
|
||||||
id="newItemImageUpload" // Unique ID
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}variant="contained" color="primary" onClick={handleAddItem}>
|
<Box sx={{ mt: 2, mb: 2 }}>
|
||||||
Add Item
|
<Typography variant="subtitle1" gutterBottom>Filter by tags:</Typography>
|
||||||
</Button>
|
<Box display="flex" flexWrap="wrap" gap={1}>
|
||||||
|
{availableTags.map(tag => (
|
||||||
{/* Dialog for adding new item */}
|
<Chip
|
||||||
|
key={tag.ID}
|
||||||
|
label={tag.name}
|
||||||
|
style={{
|
||||||
|
backgroundColor: selectedTags.includes(tag.ID) ? tag.color : 'transparent',
|
||||||
|
color: selectedTags.includes(tag.ID) ? '#fff' : 'inherit',
|
||||||
|
border: `1px solid ${tag.color}`
|
||||||
|
}}
|
||||||
|
onClick={() => handleTagSelect(tag.ID)}
|
||||||
|
clickable
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||||
|
<Typography variant="h6">
|
||||||
|
{boxName === "All Boxes" ? "All Items" : `Items in ${boxName}`}
|
||||||
|
({filteredItems.length} items)
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
||||||
|
variant="contained"
|
||||||
|
onClick={handleAddItem}
|
||||||
|
disabled={creatingItem}
|
||||||
|
>
|
||||||
|
{creatingItem ? <CircularProgress size={24} /> : 'Add Item'}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
<Dialog open={openAddItemDialog} onClose={handleCloseAddItemDialog}>
|
<Dialog open={openAddItemDialog} onClose={handleCloseAddItemDialog}>
|
||||||
<DialogTitle>Add New Item</DialogTitle>
|
<DialogTitle>Add New Item</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
|
@ -365,76 +327,58 @@ export default function Items({ token }) {
|
||||||
type="file"
|
type="file"
|
||||||
accept="image/*"
|
accept="image/*"
|
||||||
ref={fileInputRef}
|
ref={fileInputRef}
|
||||||
// capture="environment" // Capture the image from the user's camera
|
style={{ display: 'block', margin: '10px 0' }}
|
||||||
style={{ display: 'block', margin: '10px 0' }} // Style as needed
|
|
||||||
id="newItemImageUpload"
|
|
||||||
/>
|
/>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={handleCloseAddItemDialog}>Cancel</Button>
|
<Button onClick={handleCloseAddItemDialog}>Cancel</Button>
|
||||||
<Button onClick={handleSaveNewItem} color="primary">
|
<Button
|
||||||
Save
|
onClick={handleSaveNewItem}
|
||||||
|
color="primary"
|
||||||
|
disabled={creatingItem || !newItemName.trim()}
|
||||||
|
>
|
||||||
|
{creatingItem ? <CircularProgress size={24} /> : 'Save'}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
{editingItem ? (
|
|
||||||
|
{editingItem && (
|
||||||
<ItemDetails
|
<ItemDetails
|
||||||
item={editingItem}
|
item={editingItem}
|
||||||
token={token}
|
token={token}
|
||||||
onSave={handleSaveEdit}
|
onSave={handleSaveEdit}
|
||||||
onClose={handleCloseItemDetails}
|
onClose={() => setEditingItem(null)}
|
||||||
boxId={boxId}
|
boxId={boxId}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loadingItems ? (
|
||||||
|
<CircularProgress />
|
||||||
) : (
|
) : (
|
||||||
<TableContainer>
|
<TableContainer>
|
||||||
<Table>
|
<Table>
|
||||||
<TableHead>
|
<TableHead>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell style={{ width: '40px' }}>Image</TableCell>
|
<TableCell style={{ width: '40px' }}>Image</TableCell>
|
||||||
<TableCell style={{ width: '100px' }}>Name</TableCell>
|
<TableCell style={{ width: '100px' }}>Name</TableCell>
|
||||||
<TableCell>Description</TableCell>
|
<TableCell>Description</TableCell>
|
||||||
<TableCell>Actions</TableCell>
|
<TableCell>Tags</TableCell>
|
||||||
</TableRow>
|
<TableCell>Actions</TableCell>
|
||||||
</TableHead>
|
</TableRow>
|
||||||
<TableBody>
|
</TableHead>
|
||||||
{items
|
<TableBody>
|
||||||
.filter(item =>
|
{filteredItems.map((item) => (
|
||||||
item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
<Item
|
||||||
item.description.toLowerCase().includes(searchQuery.toLowerCase())
|
key={item.ID}
|
||||||
)
|
item={item}
|
||||||
.map((item) => (
|
itemImages={itemImages}
|
||||||
<TableRow key={item.ID}>
|
onDelete={handleDeleteItem}
|
||||||
<TableCell>
|
onEdit={handleEditItem}
|
||||||
<Avatar src={itemImages[item.ID] || '/images/default.jpg'} />
|
/>
|
||||||
</TableCell>
|
|
||||||
<TableCell>{item.name}</TableCell>
|
|
||||||
<TableCell>{item.description}</TableCell>
|
|
||||||
<Box display="flex" justifyContent="space-between" width="100%">
|
|
||||||
<Tooltip title="Edit Item">
|
|
||||||
<IconButton
|
|
||||||
onClick={() => handleEditItem(item)}
|
|
||||||
size="large"
|
|
||||||
sx={{ mr: 1 }}
|
|
||||||
>
|
|
||||||
<EditIcon />
|
|
||||||
</IconButton>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip title="Delete Item">
|
|
||||||
<IconButton
|
|
||||||
onClick={() => handleDeleteItem(item.ID)}
|
|
||||||
size="large"
|
|
||||||
color="error"
|
|
||||||
>
|
|
||||||
<DeleteIcon />
|
|
||||||
</IconButton>
|
|
||||||
</Tooltip>
|
|
||||||
</Box>
|
|
||||||
</TableRow>
|
|
||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</TableContainer>
|
</TableContainer>
|
||||||
)}
|
)}
|
||||||
</Container>
|
</Container>
|
||||||
);
|
)};
|
||||||
}
|
|
|
@ -1,27 +1,26 @@
|
||||||
// src/components/Login.js
|
// src/components/Login.js
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Button, TextField, Container, Typography, Alert } from '@mui/material';
|
import { Button, TextField, Container, Typography, Alert, CircularProgress } from '@mui/material';
|
||||||
import axios from 'axios';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { useNavigate } from 'react-router-dom'; // Import useNavigate
|
|
||||||
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
||||||
|
import { api } from '../services/api';
|
||||||
|
import { useApiCall } from './hooks/useApiCall';
|
||||||
|
|
||||||
export default function Login({ setToken }) {
|
export default function Login({ setToken }) {
|
||||||
const [username, setUsername] = useState('');
|
const [username, setUsername] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [loginError, setLoginError] = useState(false); // State for login error
|
const navigate = useNavigate();
|
||||||
const navigate = useNavigate(); // Initialize useNavigate
|
const { execute, loading, error } = useApiCall();
|
||||||
|
|
||||||
const handleLogin = async (e) => {
|
const handleLogin = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setLoginError(false); // Reset error state on each login attempt
|
|
||||||
try {
|
try {
|
||||||
// eslint-disable-next-line no-template-curly-in-string
|
const response = await execute(() => api.login({ username, password }));
|
||||||
const response = await axios.post(`${process.env.REACT_APP_API_URL}/login`, { username, password });
|
setToken(response.data.token);
|
||||||
setToken(response.data.token);
|
navigate('/boxes');
|
||||||
navigate('/boxes');
|
} catch (err) {
|
||||||
} catch (error) {
|
// Error handling is now managed by useApiCall
|
||||||
console.error('Login failed', error);
|
console.error('Login attempt failed');
|
||||||
setLoginError(true); // Set error state if login fails
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -29,9 +28,10 @@ export default function Login({ setToken }) {
|
||||||
<Container maxWidth="xs">
|
<Container maxWidth="xs">
|
||||||
<Typography variant="h4" gutterBottom>Login</Typography>
|
<Typography variant="h4" gutterBottom>Login</Typography>
|
||||||
|
|
||||||
{/* Display error message if loginError is true */}
|
{error && (
|
||||||
{loginError && (
|
<Alert severity="error">
|
||||||
<Alert severity="error">Login Failed</Alert>
|
{error.status === 401 ? 'Invalid username or password' : error.message}
|
||||||
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<form onSubmit={handleLogin}>
|
<form onSubmit={handleLogin}>
|
||||||
|
@ -52,10 +52,17 @@ export default function Login({ setToken }) {
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
/>
|
/>
|
||||||
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" type="submit" fullWidth>
|
<Button
|
||||||
Login
|
sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }}
|
||||||
|
variant="contained"
|
||||||
|
color="primary"
|
||||||
|
type="submit"
|
||||||
|
fullWidth
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
{loading ? <CircularProgress size={24} /> : 'Login'}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
|
@ -33,10 +33,10 @@ export default function Navbar() {
|
||||||
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
|
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
|
||||||
Boxes
|
Boxes
|
||||||
</Typography>
|
</Typography>
|
||||||
<Button color="inherit" component={Link} to="/login">Login</Button>
|
<Button color="inherit" component={Link} to="/api/v1/login">Login</Button>
|
||||||
<Button color="inherit" component={Link} to="/boxes">Boxes</Button>
|
<Button color="inherit" component={Link} to="/api/v1/boxes">Boxes</Button>
|
||||||
<Button color="inherit" component={Link} to="/items">Items</Button>
|
<Button color="inherit" component={Link} to="/api/v1/items">Items</Button>
|
||||||
<Button color="inherit" component={Link} to="/admin">Admin</Button>
|
<Button color="inherit" component={Link} to="/api/v1/admin">Admin</Button>
|
||||||
<Button color="inherit" onClick={handleLogout}>Logout</Button>
|
<Button color="inherit" onClick={handleLogout}>Logout</Button>
|
||||||
</Toolbar>
|
</Toolbar>
|
||||||
</AppBar>
|
</AppBar>
|
||||||
|
|
|
@ -0,0 +1,43 @@
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* useApiCall hook.
|
||||||
|
*
|
||||||
|
* This hook helps to wrap API calls in a way that makes it easier to manage
|
||||||
|
* loading state and errors.
|
||||||
|
*
|
||||||
|
* @returns {Object} An object with `execute`, `loading`, and `error`
|
||||||
|
* properties. `execute` is a function that wraps the API call and sets the
|
||||||
|
* `loading` and `error` states accordingly. `loading` is a boolean that is
|
||||||
|
* `true` while the API call is in progress and `false` otherwise. `error` is
|
||||||
|
* `null` if the API call was successful and an error object if the API call
|
||||||
|
* failed.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const { execute, loading, error } = useApiCall();
|
||||||
|
*
|
||||||
|
* const fetchData = async () => {
|
||||||
|
* const response = await execute(api.items.getAll());
|
||||||
|
* // Do something with the response
|
||||||
|
* };
|
||||||
|
*/
|
||||||
|
export const useApiCall = () => {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
|
const execute = async (apiCall) => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await apiCall();
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
setError(err);
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return { execute, loading, error };
|
||||||
|
};
|
|
@ -0,0 +1,181 @@
|
||||||
|
import React, { useState, useEffect, useCallback } from 'react';
|
||||||
|
import {
|
||||||
|
Chip,
|
||||||
|
Dialog,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContent,
|
||||||
|
DialogActions,
|
||||||
|
TextField,
|
||||||
|
Button,
|
||||||
|
Box,
|
||||||
|
CircularProgress,
|
||||||
|
Alert
|
||||||
|
} from '@mui/material';
|
||||||
|
import { LocalOffer as TagIcon } from '@mui/icons-material';
|
||||||
|
import { useApiCall } from './hooks/useApiCall';
|
||||||
|
import { api } from '../services/api';
|
||||||
|
|
||||||
|
const TagManager = React.memo(({ token, itemId, initialTags = [], onTagsChange }) => {
|
||||||
|
const [tags, setTags] = useState([]);
|
||||||
|
const [itemTags, setItemTags] = useState(initialTags);
|
||||||
|
const [openDialog, setOpenDialog] = useState(false);
|
||||||
|
const [newTagName, setNewTagName] = useState('');
|
||||||
|
const [newTagDescription, setNewTagDescription] = useState('');
|
||||||
|
const [newTagColor, setNewTagColor] = useState('#3366ff');
|
||||||
|
|
||||||
|
const { execute: fetchTags, loading: loadingTags, error: tagsError } = useApiCall();
|
||||||
|
const { execute: createTag, loading: creatingTag, error: createError } = useApiCall();
|
||||||
|
const { execute: addTags, loading: addingTags, error: addError } = useApiCall();
|
||||||
|
const { execute: removeTag, loading: removingTag, error: removeError } = useApiCall();
|
||||||
|
|
||||||
|
// Only fetch tags once when component mounts
|
||||||
|
useEffect(() => {
|
||||||
|
const getTags = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetchTags(() => api.tags.getAll(token));
|
||||||
|
setTags(response.data);
|
||||||
|
} catch (err) {}
|
||||||
|
};
|
||||||
|
getTags();
|
||||||
|
}, []); // Empty dependency array - only run once on mount
|
||||||
|
|
||||||
|
// Update itemTags when initialTags prop changes
|
||||||
|
useEffect(() => {
|
||||||
|
setItemTags(initialTags);
|
||||||
|
}, [initialTags]);
|
||||||
|
|
||||||
|
const handleCreateTag = async () => {
|
||||||
|
try {
|
||||||
|
const response = await createTag(() => api.tags.create(token, {
|
||||||
|
name: newTagName,
|
||||||
|
description: newTagDescription,
|
||||||
|
color: newTagColor
|
||||||
|
}));
|
||||||
|
setTags(prevTags => [...prevTags, response.data]);
|
||||||
|
setOpenDialog(false);
|
||||||
|
setNewTagName('');
|
||||||
|
setNewTagDescription('');
|
||||||
|
setNewTagColor('#3366ff');
|
||||||
|
} catch (err) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddTag = async (tagId) => {
|
||||||
|
if (!itemId) return;
|
||||||
|
try {
|
||||||
|
await addTags(() => api.items.addTags(token, itemId, [tagId]));
|
||||||
|
const newTag = tags.find(t => t.ID === tagId);
|
||||||
|
if (newTag) {
|
||||||
|
const updatedTags = [...itemTags, newTag];
|
||||||
|
setItemTags(updatedTags);
|
||||||
|
onTagsChange?.(updatedTags);
|
||||||
|
}
|
||||||
|
} catch (err) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveTag = async (tagId) => {
|
||||||
|
if (!itemId) return;
|
||||||
|
try {
|
||||||
|
await removeTag(() => api.items.removeTag(token, itemId, tagId));
|
||||||
|
const updatedTags = itemTags.filter(tag => tag.ID !== tagId);
|
||||||
|
setItemTags(updatedTags);
|
||||||
|
onTagsChange?.(updatedTags);
|
||||||
|
} catch (err) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
{(tagsError || createError || addError || removeError) && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
{tagsError?.message || createError?.message ||
|
||||||
|
addError?.message || removeError?.message}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box display="flex" alignItems="center" flexWrap="wrap" gap={1}>
|
||||||
|
{itemTags.map(tag => (
|
||||||
|
<Chip
|
||||||
|
key={tag.ID}
|
||||||
|
label={tag.name}
|
||||||
|
onDelete={() => handleRemoveTag(tag.ID)}
|
||||||
|
style={{
|
||||||
|
backgroundColor: tag.color,
|
||||||
|
color: '#fff'
|
||||||
|
}}
|
||||||
|
disabled={removingTag}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Box sx={{ ml: 1 }}>
|
||||||
|
{loadingTags ? (
|
||||||
|
<CircularProgress size={24} />
|
||||||
|
) : (
|
||||||
|
tags
|
||||||
|
.filter(tag => !itemTags.find(it => it.ID === tag.ID))
|
||||||
|
.map(tag => (
|
||||||
|
<Chip
|
||||||
|
key={tag.ID}
|
||||||
|
label={tag.name}
|
||||||
|
onClick={() => handleAddTag(tag.ID)}
|
||||||
|
style={{
|
||||||
|
backgroundColor: tag.color,
|
||||||
|
color: '#fff',
|
||||||
|
margin: '0 4px'
|
||||||
|
}}
|
||||||
|
disabled={addingTags}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
startIcon={<TagIcon />}
|
||||||
|
variant="outlined"
|
||||||
|
size="small"
|
||||||
|
onClick={() => setOpenDialog(true)}
|
||||||
|
sx={{ ml: 1 }}
|
||||||
|
>
|
||||||
|
New Tag
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Dialog open={openDialog} onClose={() => setOpenDialog(false)}>
|
||||||
|
<DialogTitle>Create New Tag</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<TextField
|
||||||
|
label="Name"
|
||||||
|
value={newTagName}
|
||||||
|
onChange={(e) => setNewTagName(e.target.value)}
|
||||||
|
fullWidth
|
||||||
|
margin="normal"
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
label="Description"
|
||||||
|
value={newTagDescription}
|
||||||
|
onChange={(e) => setNewTagDescription(e.target.value)}
|
||||||
|
fullWidth
|
||||||
|
margin="normal"
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
label="Color"
|
||||||
|
type="color"
|
||||||
|
value={newTagColor}
|
||||||
|
onChange={(e) => setNewTagColor(e.target.value)}
|
||||||
|
fullWidth
|
||||||
|
margin="normal"
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={() => setOpenDialog(false)}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleCreateTag}
|
||||||
|
disabled={creatingTag || !newTagName.trim()}
|
||||||
|
>
|
||||||
|
{creatingTag ? <CircularProgress size={24} /> : 'Create'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default TagManager;
|
|
@ -0,0 +1,134 @@
|
||||||
|
import React from 'react';
|
||||||
|
import { createTheme, ThemeProvider, CssBaseline } from '@mui/material';
|
||||||
|
import { grey, blue } from '@mui/material/colors';
|
||||||
|
|
||||||
|
// Enhanced theme with better visual hierarchy and modern styling
|
||||||
|
const theme = createTheme({
|
||||||
|
palette: {
|
||||||
|
mode: 'light',
|
||||||
|
primary: {
|
||||||
|
main: blue[700],
|
||||||
|
dark: blue[900],
|
||||||
|
light: blue[500],
|
||||||
|
contrastText: '#fff'
|
||||||
|
},
|
||||||
|
background: {
|
||||||
|
default: grey[100],
|
||||||
|
paper: '#fff'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
typography: {
|
||||||
|
h1: {
|
||||||
|
fontSize: '2.5rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
marginBottom: '1.5rem'
|
||||||
|
},
|
||||||
|
h2: {
|
||||||
|
fontSize: '2rem',
|
||||||
|
fontWeight: 500,
|
||||||
|
marginBottom: '1.25rem'
|
||||||
|
},
|
||||||
|
h3: {
|
||||||
|
fontSize: '1.75rem',
|
||||||
|
fontWeight: 500,
|
||||||
|
marginBottom: '1rem'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
components: {
|
||||||
|
MuiButton: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
textTransform: 'none',
|
||||||
|
borderRadius: 8,
|
||||||
|
padding: '8px 16px',
|
||||||
|
fontWeight: 500
|
||||||
|
},
|
||||||
|
contained: {
|
||||||
|
boxShadow: 'none',
|
||||||
|
'&:hover': {
|
||||||
|
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MuiCard: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
borderRadius: 12,
|
||||||
|
boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
|
||||||
|
'&:hover': {
|
||||||
|
boxShadow: '0 4px 12px rgba(0,0,0,0.12)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MuiTextField: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
'& .MuiOutlinedInput-root': {
|
||||||
|
borderRadius: 8,
|
||||||
|
backgroundColor: '#fff',
|
||||||
|
'&:hover fieldset': {
|
||||||
|
borderColor: blue[400]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MuiTable: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
backgroundColor: '#fff',
|
||||||
|
borderRadius: 12,
|
||||||
|
overflow: 'hidden'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MuiTableHead: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
backgroundColor: grey[50]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MuiTableCell: {
|
||||||
|
styleOverrides: {
|
||||||
|
head: {
|
||||||
|
fontWeight: 600,
|
||||||
|
color: grey[900]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Layout component for consistent padding and max-width
|
||||||
|
const Layout = ({ children }) => (
|
||||||
|
<div className="p-6 max-w-7xl mx-auto">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
// Enhanced page container with proper spacing and background
|
||||||
|
const PageContainer = ({ children, title }) => (
|
||||||
|
<div className="min-h-screen bg-gray-100">
|
||||||
|
<Layout>
|
||||||
|
{title && <h1 className="text-3xl font-semibold mb-6">{title}</h1>}
|
||||||
|
<div className="bg-white rounded-xl shadow-sm p-6">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</Layout>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
export function EnhancedThemeProvider({ children }) {
|
||||||
|
return (
|
||||||
|
<ThemeProvider theme={theme}>
|
||||||
|
<CssBaseline />
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Layout, PageContainer };
|
||||||
|
export default EnhancedThemeProvider;
|
|
@ -4,6 +4,11 @@ import './index.css';
|
||||||
import App from './App';
|
import App from './App';
|
||||||
import reportWebVitals from './reportWebVitals';
|
import reportWebVitals from './reportWebVitals';
|
||||||
|
|
||||||
|
const path = window.location.pathname;
|
||||||
|
if (path !== '/' && !path.startsWith('/api/v1/')) {
|
||||||
|
window.history.replaceState(null, '', '/');
|
||||||
|
}
|
||||||
|
|
||||||
// Log the environment variables
|
// Log the environment variables
|
||||||
console.log('REACT_APP_API_URL:', process.env.REACT_APP_API_URL);
|
console.log('REACT_APP_API_URL:', process.env.REACT_APP_API_URL);
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,92 @@
|
||||||
|
// src/services/api.js
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
const createApiClient = () => {
|
||||||
|
const client = axios.create({
|
||||||
|
baseURL: process.env.REACT_APP_API_URL
|
||||||
|
});
|
||||||
|
|
||||||
|
const authHeader = (token) => ({ Authorization: `Bearer ${token}` });
|
||||||
|
|
||||||
|
return {
|
||||||
|
// Auth
|
||||||
|
login: (credentials) =>
|
||||||
|
client.post('/api/v1/login', credentials),
|
||||||
|
|
||||||
|
// Items
|
||||||
|
items: {
|
||||||
|
getAll: (token) =>
|
||||||
|
client.get('/api/v1/items', { headers: authHeader(token) }),
|
||||||
|
getOne: (token, id) =>
|
||||||
|
client.get(`/api/v1/items/${id}`, { headers: authHeader(token) }),
|
||||||
|
create: (token, itemData) =>
|
||||||
|
client.post('/api/v1/items', itemData, { headers: authHeader(token) }),
|
||||||
|
update: (token, id, itemData) =>
|
||||||
|
client.put(`/api/v1/items/${id}`, itemData, { headers: authHeader(token) }),
|
||||||
|
delete: (token, id) =>
|
||||||
|
client.delete(`/api/v1/items/${id}`, { headers: authHeader(token) }),
|
||||||
|
uploadImage: (token, id, formData) =>
|
||||||
|
client.post(`/api/v1/items/${id}/upload`, formData, {
|
||||||
|
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
|
||||||
|
}),
|
||||||
|
getImage: (token, id) =>
|
||||||
|
client.get(`/api/v1/items/${id}/image`, {
|
||||||
|
headers: authHeader(token),
|
||||||
|
responseType: 'blob'
|
||||||
|
}),
|
||||||
|
getByBox: (token, boxId) =>
|
||||||
|
client.get(`/api/v1/boxes/${boxId}/items`, { headers: authHeader(token) }),
|
||||||
|
addTags: (token, itemId, tagIds) =>
|
||||||
|
client.post(`/api/v1/items/${itemId}/tags`, tagIds, {
|
||||||
|
headers: authHeader(token)
|
||||||
|
}),
|
||||||
|
removeTag: (token, itemId, tagId) =>
|
||||||
|
client.delete(`/api/v1/items/${itemId}/tags/${tagId}`, {
|
||||||
|
headers: authHeader(token)
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
// Boxes
|
||||||
|
boxes: {
|
||||||
|
getAll: (token) =>
|
||||||
|
client.get('/api/v1/boxes', { headers: authHeader(token) }),
|
||||||
|
create: (token, boxData) =>
|
||||||
|
client.post('/api/v1/boxes', boxData, { headers: authHeader(token) }),
|
||||||
|
delete: (token, id) =>
|
||||||
|
client.delete(`/api/v1/boxes/${id}`, { headers: authHeader(token) }),
|
||||||
|
},
|
||||||
|
|
||||||
|
tags: {
|
||||||
|
getAll: (token) =>
|
||||||
|
client.get('/api/v1/tags', { headers: authHeader(token) }),
|
||||||
|
create: (token, tagData) =>
|
||||||
|
client.post('/api/v1/tags', tagData, { headers: authHeader(token) }),
|
||||||
|
update: (token, id, tagData) =>
|
||||||
|
client.put(`/api/v1/tags/${id}`, tagData, { headers: authHeader(token) }),
|
||||||
|
delete: (token, id) =>
|
||||||
|
client.delete(`/api/v1/tags/${id}`, { headers: authHeader(token) }),
|
||||||
|
getItems: (token, id) =>
|
||||||
|
client.get(`/api/v1/tags/${id}/items`, { headers: authHeader(token) }),
|
||||||
|
},
|
||||||
|
|
||||||
|
// Admin
|
||||||
|
admin: {
|
||||||
|
getUsers: (token) =>
|
||||||
|
client.get('/api/v1/admin/user', { headers: authHeader(token) }),
|
||||||
|
createUser: (token, userData) =>
|
||||||
|
client.post('/api/v1/admin/user', userData, { headers: authHeader(token) }),
|
||||||
|
deleteUser: (token, id) =>
|
||||||
|
client.delete(`/api/v1/admin/user/${id}`, { headers: authHeader(token) }),
|
||||||
|
backupDb: (token) =>
|
||||||
|
client.get('/api/v1/admin/db', {
|
||||||
|
headers: authHeader(token),
|
||||||
|
responseType: 'blob'
|
||||||
|
}),
|
||||||
|
restoreDb: (token, formData) =>
|
||||||
|
client.post('/api/v1/admin/db', formData, {
|
||||||
|
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const api = createApiClient();
|
|
@ -0,0 +1,36 @@
|
||||||
|
// src/utils/errorHandler.js
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(message, status, details = {}) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
this.details = details;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enhanced API client with error handling
|
||||||
|
export const createApiClient = () => {
|
||||||
|
const client = axios.create({
|
||||||
|
baseURL: process.env.REACT_APP_API_URL
|
||||||
|
});
|
||||||
|
|
||||||
|
client.interceptors.response.use(
|
||||||
|
response => response,
|
||||||
|
error => {
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
window.location.href = '/login';
|
||||||
|
return Promise.reject(new ApiError('Session expired', 401));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.reject(new ApiError(
|
||||||
|
error.response?.data?.message || 'An error occurred',
|
||||||
|
error.response?.status,
|
||||||
|
error.response?.data
|
||||||
|
));
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return client;
|
||||||
|
};
|
|
@ -0,0 +1,18 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Set the username and password
|
||||||
|
USERNAME="boxuser"
|
||||||
|
PASSWORD="boxuser"
|
||||||
|
EMAIL="boxuser@r8z.us"
|
||||||
|
|
||||||
|
# Set the database file and table name
|
||||||
|
DB_FILE="../boxes-api/data/boxes.db"
|
||||||
|
TABLE_NAME="users"
|
||||||
|
|
||||||
|
# Generate the bcrypt encrypted password using htpasswd
|
||||||
|
ENCRYPTED_PASSWORD=$(htpasswd -bnBC 10 "" "$PASSWORD" | tr -d ':\n')
|
||||||
|
|
||||||
|
# Insert the username and encrypted password into the database
|
||||||
|
sqlite3 "$DB_FILE" "INSERT INTO $TABLE_NAME (username, password, email) VALUES ('$USERNAME', '$ENCRYPTED_PASSWORD', '$EMAIL')"
|
||||||
|
|
||||||
|
echo "Password encrypted and stored in the database."
|
Loading…
Reference in New Issue