Skip to content

Commit

Permalink
Add Documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Crispy-rw committed Jun 2, 2023
1 parent a626fe1 commit f7c2639
Show file tree
Hide file tree
Showing 14 changed files with 730 additions and 35 deletions.
78 changes: 78 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
title: Energize Swap Backend API
---

# Energize Swap Backend API

The Energize Swap Backend API is a RESTful API designed to manage battery swapping operations for electric vehicles. It provides endpoints for creating and managing drivers, batteries, swap stations, and battery swaps.

## Features

- **Driver Management:** Register new drivers and retrieve driver information.
- **Battery Management:** Add batteries, track battery locations, and monitor battery status.
- **Swap Station Management:** Create and manage swap stations, including their locations and available batteries.
- **Battery Swap Operations:** Perform battery swaps by associating a driver with a battery and a swap station.

## Technologies Used

- **Python:** The backend is implemented in Python, utilizing the Flask framework.
- **SQLAlchemy:** The database is managed using SQLAlchemy, an Object-Relational Mapping (ORM) library.
- **MySql:** The default database is MySql, but it can be easily switched to other supported databases.
- **RESTful API:** The API follows RESTful principles, allowing easy integration with frontend and mobile applications.
- **Docker:** The project includes a Docker Compose configuration for easy deployment.

## Installation and Setup

To set up the Energize Swap Backend API, follow these steps:

1. Clone the repository: `git clone https://github.com/your/repo.git`
2. Install the required dependencies: `pip install -r requirements.txt`
3. Set up the database: `python manage.py db upgrade`
4. Start the development server: `python app.py`

The API will be accessible at `http://localhost:5000`.

## API ENDPOINTS

| Ressource URL | Methods | Description | Authentication required |
| -------------------------------- | ------- | ----------------------------------------------- | ----------------------- |
| /api/v1/batteries | GET | Get a list of all batteries | Yes |
| /api/v1/batteries/addbattery | POST | Create a new battery | Yes |
| /api/v1/drivers | GET | GET a list of drivers | Yes |
| /api/v1/drivers/addriver | POST | Create a new driver | Yes |
| /api/v1/stations | GET | Get a list of stations | No |
| /api/v1/stations/addstation | POST | Create a new Station | Yes |
| /api/v1/stations/batteries | GET | Get all batteries of a specific stations | Yes |
| /api/v1/swaps | GET | Get a list of all battery exchange | Yes |
| /api/v1/swaps/addswap | POST | Create a new battery exchange | Yes |
| /api/v1/swaps/stopswap/<swap_id> | PUT | Modify/Edit a specific swap to finish it | Yes |
| /api/v1/swaps/totalswappedbattery| GET | Get a list of total battery exchanged | Yes |
| /api/v1/swaps/<swap_id> | GET | Get information of one battery exchange | Yes |
| /api/v1/movements/<serial_number>| POST | Update the movement of an active battery | Yes |
| /api/v1/login | POST | Authentication | No |

## Deployment

The Energize Swap Backend API can be deployed to various environments, such as local servers, cloud platforms, or containerized environments. The project includes a Docker Compose configuration file that simplifies the deployment process.

To deploy using Docker Compose, follow these steps:

1. Install Docker and Docker Compose.
2. Build the Docker image: `docker-compose build`
3. Start the Docker containers: `docker-compose up -d`

The API will be accessible at `http://localhost:5000`.

## Contributing

Contributions to the Energize Swap Backend API project are welcome! If you find any issues or have suggestions for improvements, please create an issue or submit a pull request. Make sure to follow the project's code style and guidelines.

## License

The Energize Swap Backend API is released under the [MIT License](https://opensource.org/licenses/MIT). You are free to use, modify, and distribute the code for both commercial and non-commercial purposes. See the `LICENSE` file for more details.

## Acknowledgments

This project was developed as part of the Energize Swap initiative to promote electric vehicle adoption and provide efficient battery swapping services. We would like to thank all the contributors and supporters who have made this project possible.

For any inquiries or further information, please contact [Project Team Email].
25 changes: 10 additions & 15 deletions backend/api/v1/views/swaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,22 @@ def create_battery_swap():
"message": "Driver in movement",
}), 400

swap = Swap.save(
{
swap = Swap.save( {
"battery_id": sent_data["battery"],
"driver_id": sent_data["driver"],
"station_id": user_info["station_id"],
}
)
return jsonify(
{
})

return jsonify({
"status": "Ok",
"message": "New battery Swap Created",
"data": swap.serialize_one,
}
), 201
}), 201

except Exception:
return jsonify(
{
"status": "Error",
"message": "Error creating a new battery swap",
}
),400
return jsonify({"status": "Error",
"message": "Error creating a new battery swap",
}),400


@app_views.route("swaps", methods=["GET"], strict_slashes=False)
Expand Down Expand Up @@ -121,7 +116,7 @@ def get_finished_swaps():
if user_info is False:
return jsonify({
'status': "Error",
"message": "Invalid Token {}"
"message": "Invalid Token"
}), 400

station_id = user_info.get("station_id", None)
Expand Down
4 changes: 3 additions & 1 deletion frontend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ COPY ./yarn.lock ./

RUN yarn install

RUN yarn build

COPY . .

EXPOSE 5173

CMD ["yarn", "start"]
CMD ["npx", "serve", "build/", "-l", "5173"]
66 changes: 66 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
title: Energize Swap Frontend
---

# Energize Swap Frontend

The Energize Swap Frontend is a user interface built using modern web technologies to interact with the Energize Swap Backend API. It provides a user-friendly interface for managing drivers, batteries, swap stations, and battery swaps.

## Features

- **Driver Management:** Register new drivers, view driver information, and update driver details.
- **Battery Management:** Add new batteries, track battery locations, and monitor battery status.
- **Swap Station Management:** Create and manage swap stations, view station details, and assign batteries to stations.
- **Battery Swap Operations:** Perform battery swaps, initiate battery movement, and track ongoing and completed swaps.

## Technologies Used

- **React:** The frontend is developed using the React library, providing a component-based architecture for building user interfaces.
- **Redux:** Redux is used for state management, enabling efficient data flow and synchronization with the backend API.
- **React Router:** React Router is utilized for client-side routing, allowing seamless navigation between different pages and components.
- **Fetch:** Fetch is used for making HTTP requests to the backend API, facilitating data retrieval and modification.
- **@mui/material:** Material UI is employed for styling and theming the frontend components, providing an aesthetic and responsive design.

## Installation and Setup

To set up the Energize Swap Frontend, follow these steps:

1. Clone the repository: `git clone https://github.com/your/repo.git`
2. Install the required dependencies: `yarn install`
3. Configure the backend API endpoint: Update the API endpoint in the configuration file (`src/config.js`) to match your backend server address.
4. Start the development server: `yarn start`

The frontend will be accessible at `http://localhost:5173`.

## Folder Structure

The frontend project follows a modular folder structure, allowing easy organization and maintenance of the codebase. Here's an overview of the main folders:

- `src/components`: Contains reusable UI components used throughout the application.
- `src/pages`: Contains the main application pages, each representing a specific route.
- `src/redux`: Includes Redux actions, reducers, and store configuration for managing application state.
- `src/services`: Contains service modules for interacting with the backend API.
- `src/configs`: Includes utility functions and helper modules used across the application.
- `src/routes`: Contains configuration for all pages routes

## Deployment

The Energize Swap Frontend can be deployed to various hosting platforms or integrated into existing web applications. It's recommended to build the production version of the frontend before deployment.

To build the production version, run: `npm run build`

This command will generate optimized and minified static files in the `build` directory. You can then deploy these files to a static file server or integrate them with your backend server.

## Contributing

Contributions to the Energize Swap Frontend project are welcome! If you encounter any issues or have suggestions for improvements, please create an issue or submit a pull request. Make sure to follow the project's coding style and guidelines.

## License

The Energize Swap Frontend is released under the [MIT License](https://opensource.org/licenses/MIT). You are free to use, modify, and distribute the code for both commercial and non-commercial purposes. See the `LICENSE` file for more details.

## Acknowledgments

This project was developed as part of the Energize Swap initiative to promote electric vehicle adoption and provide efficient battery swapping services. We extend our gratitude to all the contributors and supporters who have made this project possible.

For any inquiries or further information, please contact [[email protected]].
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"react-router-dom": "^6.4.3",
"react-toastify": "^9.1.3",
"safe-buffer": "^5.2.1",
"serve": "^14.2.0",
"typescript": "^4.4.2",
"web-vitals": "^2.1.0"
},
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/components/common/Sidebar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ const Sidebar = () => {

const logout = () => {
localStorage.removeItem("token");
window.location.replace("/login");
window.location.replace("/").then(()=>{
window.location.reload();
});
};

return (
Expand Down
1 change: 1 addition & 0 deletions frontend/src/configs/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const BASE_URL = 'http://localhost:5000/api/v1/'
2 changes: 1 addition & 1 deletion frontend/src/pages/Battery/BatteriesPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ const BatteriesPage = (props) => {
<Box sx={style}>
<div style={headerStyles}>
<Typography fontSize={"20px"}>Create a new battery</Typography>
<CloseIcon />
<CloseIcon onClick={handleClose} />
</div>
<form onSubmit={handleSubmit(onSubmit)} style={formStyle}>
<TextField
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/Driver/DriversPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ const DriversPage = (props) => {
<Typography fontSize={"20px"}>
Add New Driver
</Typography>
<CloseIcon />
<CloseIcon onClick={handleClose} />
</div>
<form
onSubmit={handleSubmit(onSubmit)}
Expand Down
23 changes: 13 additions & 10 deletions frontend/src/pages/Login/LoginPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Button, MenuItem, TextField, Typography } from "@mui/material";
import { toast } from "react-toastify"

import "./login.css";
import { BASE_URL } from "../../configs";

function TabPanel(props) {
const { children, value, index, ...other } = props;
Expand Down Expand Up @@ -73,7 +74,7 @@ function LoginPage() {

React.useEffect(() => {
function getStations() {
fetch("http://localhost:5000/api/v1/stations", {
fetch(`${BASE_URL}stations`, {
method: "GET",
headers: { "Content-Type": "application/json" },
})
Expand All @@ -82,7 +83,9 @@ function LoginPage() {
setStations(json?.data);
})
.catch((err) => {
console.log(err);
toast.error(err.message,{
position: toast.POSITION.TOP_RIGHT
})
});
}
getStations();
Expand All @@ -104,22 +107,22 @@ function LoginPage() {
return res.json();
}
res.json().then( res => {
toast.error(res?.message, {
toast.error(res?.error, {
position: toast.POSITION.TOP_RIGHT
});
})
throw new Error(res.statusText);
})
.then(({ token }) => {
localStorage.setItem("token", token);
if (!data?.station) {
window.location.replace("/admin/drivers");
} else {
window.location.replace("/manager/swaps/ongoing");
if (data) {
window.location.replace("/");
}
})
};

console.log("))))))))))", errors)

return (
<>
<section className="form-section">
Expand All @@ -145,10 +148,10 @@ function LoginPage() {
variant="filled"
fullWidth
type="email"
required
// required
label="Email"
{...register("email", {
required: true,
required: "Email is required",
maxLength: 20,
minLength: 3,
})}
Expand All @@ -163,7 +166,7 @@ function LoginPage() {
variant="filled"
id="outlined-password-input"
label="Password"
required
// required
type="password"
autoComplete="current-password"
{...register("password", {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/Station/StationsPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export default function StationsPage(props) {
<Box sx={style}>
<div style={headerStyles}>
<Typography fontSize={"20px"}>Add New Station</Typography>
<CloseIcon />
<CloseIcon onClick={handleClose} />
</div>
<form onSubmit={handleSubmit(onSubmit)} style={formStyle}>
<TextField
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
import { Button, Stack } from "@mui/material";
import { Controller, useForm } from "react-hook-form";
import { formatTime } from "../../configs/helpers";
import { toast } from "react-toastify";

const style = {
position: "absolute",
Expand Down Expand Up @@ -114,6 +115,9 @@ const StationBatteryMovementPage = () => {
})
.catch((err) => {
console.log("Err creating a new swap", err);
toast.error(err?.data?.message, {
position: toast.POSITION.TOP_RIGHT
})
});
};

Expand All @@ -128,7 +132,9 @@ const StationBatteryMovementPage = () => {
refetch();
})
.catch((err) => {
console.log("===>>>", err);
toast.error(err?.data?.message, {
position: toast.POSITION.TOP_RIGHT
})
});
};

Expand Down Expand Up @@ -215,7 +221,7 @@ const StationBatteryMovementPage = () => {
<Box sx={style}>
<div style={headerStyles}>
<Typography fontSize={"20px"}>New Battery Swap Form</Typography>
<CloseIcon />
<CloseIcon onClick={handleClose} />
</div>
<form onSubmit={handleSubmit(onSubmit)} style={formStyle}>
<Controller
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/redux/features/apiSlice.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {createApi, fetchBaseQuery} from "@reduxjs/toolkit/query/react"

import { BASE_URL } from "../../configs";


const baseQuery = fetchBaseQuery({
baseUrl: 'http://localhost:5000/api/v1/',
baseUrl: BASE_URL,
prepareHeaders: headers => {

const token = localStorage.getItem('token');
Expand Down
Loading

0 comments on commit f7c2639

Please sign in to comment.