0% found this document useful (0 votes)
2 views

Cab Booking

The document outlines the structure and components of a CAB Booking system's backend, detailing the Java package organization, including controllers, services, entities, and configuration files. Key functionalities include user registration, driver management, booking creation, and payment processing, with security measures implemented through JWT authentication. Exception handling is also addressed with custom exceptions and a global exception handler.

Uploaded by

Ahamed Rmd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Cab Booking

The document outlines the structure and components of a CAB Booking system's backend, detailing the Java package organization, including controllers, services, entities, and configuration files. Key functionalities include user registration, driver management, booking creation, and payment processing, with security measures implemented through JWT authentication. Exception handling is also addressed with custom exceptions and a global exception handler.

Uploaded by

Ahamed Rmd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 40

CAB Booking system

-------------------

Backend Coding structure:


==========================

com.cabbooking
├── CabBookingApplication.java
├── config
│ ├── JwtAuthenticationFilter.java
│ ├── SecurityConfig.java
├── controller
│ ├── UserController.java
│ ├── DriverController.java
│ ├── BookingController.java
│ ├── PaymentController.java
├── dto
│ ├── UserDTO.java
│ ├── BookingDTO.java
├── entity
│ ├── User.java
│ ├── Driver.java
│ ├── Booking.java
│ ├── Payment.java
├── exception
│ ├── CustomException.java
│ ├── GlobalExceptionHandler.java
├── repository
│ ├── UserRepository.java
│ ├── DriverRepository.java
│ ├── BookingRepository.java
│ ├── PaymentRepository.java
├── service
│ ├── UserService.java
│ ├── BookingService.java
│ ├── PaymentService.java
│ ├── impl
│ ├── UserServiceImpl.java
│ ├── BookingServiceImpl.java
│ ├── PaymentServiceImpl.java
└── util
├── JwtUtil.java

CabBookingApplication.java
===========================

@SpringBootApplication
public class CabBookingApplication {
public static void main(String[] args) {
SpringApplication.run(CabBookingApplication.class, args);
}
}

JwtAuthenticationFilter.java
=============================
package com.cabbooking.config;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {


private final JwtUtil jwtUtil;

public JwtAuthenticationFilter(JwtUtil jwtUtil) {


this.jwtUtil = jwtUtil;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain chain)
throws ServletException, IOException {
String token = jwtUtil.extractToken(request);
if (token != null && jwtUtil.validateToken(token)) {

SecurityContextHolder.getContext().setAuthentication(jwtUtil.getAuthentication(toke
n));
}
chain.doFilter(request, response);
}
}

SecurityConfig.java
====================

package com.cabbooking.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import
org.springframework.security.config.annotation.authentication.builders.Authenticati
onManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilte
r;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http,
JwtAuthenticationFilter jwtFilter) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtFilter,
UsernamePasswordAuthenticationFilter.class);
return http.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

UserController.java
===================

package com.cabbooking.controller;

import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

@Autowired
private UserService userService;

@PostMapping("/register")
public ResponseEntity<User> registerUser(@RequestBody UserDTO userDTO) {
return ResponseEntity.ok(userService.registerUser(userDTO));
}

@GetMapping("/profile")
public ResponseEntity<User> getUserProfile(@RequestParam String email) {
return ResponseEntity.ok(userService.getUserProfile(email));
}
}

DriverController.java
======================

package com.cabbooking.controller;

import com.cabbooking.entity.Driver;
import com.cabbooking.repository.DriverRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/driver")
public class DriverController {

@Autowired
private DriverRepository driverRepository;

@PostMapping("/register")
public ResponseEntity<Driver> registerDriver(@RequestBody Driver driver) {
return ResponseEntity.ok(driverRepository.save(driver));
}

@GetMapping("/{id}")
public ResponseEntity<Driver> getDriver(@PathVariable Long id) {
return ResponseEntity.ok(driverRepository.findById(id).orElseThrow(() ->
new RuntimeException("Driver not found")));
}
}

BookingController.java
======================

package com.cabbooking.controller;

import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.service.BookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/booking")
public class BookingController {

@Autowired
private BookingService bookingService;

@PostMapping("/create")
public ResponseEntity<Booking> createBooking(@RequestBody BookingDTO
bookingDTO) {
return ResponseEntity.ok(bookingService.createBooking(bookingDTO));
}
}

PaymentController.java
=======================

package com.cabbooking.controller;

import com.cabbooking.entity.Payment;
import com.cabbooking.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/payment")
public class PaymentController {

@Autowired
private PaymentService paymentService;

@PostMapping("/process")
public ResponseEntity<Payment> processPayment(@RequestParam Long bookingId,
@RequestParam double amount) {
return ResponseEntity.ok(paymentService.processPayment(bookingId, amount));
}
}

UserDTO.java
=============

package com.cabbooking.dto;

public class UserDTO {


private String name;
private String email;
private String password;

// Default Constructor
public UserDTO() {
}

// Parameterized Constructor
public UserDTO(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}

// Getters and Setters


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getPassword() {


return password;
}
public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return "UserDTO{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}

BookingDTO.java
================

package com.gmail.dto;

public class BookingDTO {


private Long id;
private String user;
private String date;
private String time;

// Default Constructor
public BookingDTO() {
}

// Parameterized Constructor
public BookingDTO(Long id, String user, String date, String time) {
this.id = id;
this.user = user;
this.date = date;
this.time = time;
}

// Getters and Setters


public Long getId() {
return id;
}

public void setId(Long id) {


this.id = id;
}

public String getUser() {


return user;
}

public void setUser(String user) {


this.user = user;
}

public String getDate() {


return date;
}
public void setDate(String date) {
this.date = date;
}

public String getTime() {


return time;
}

public void setTime(String time) {


this.time = time;
}

@Override
public String toString() {
return "BookingDTO{" +
"id=" + id +
", user='" + user + '\'' +
", date='" + date + '\'' +
", time='" + time + '\'' +
'}';
}
}

User.java
============

package com.cabbooking.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String username;


private String password;
private String email;
private String role;

public User() {}

public User(String username, String password, String email, String role) {


this.username = username;
this.password = password;
this.email = email;
this.role = role;
}

public Long getId() {


return id;
}
public void setId(Long id) {
this.id = id;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getRole() {


return role;
}

public void setRole(String role) {


this.role = role;
}

@Override
public String toString() {
return "User{id=" + id + ", username='" + username + "', email='" + email +
"', role='" + role + "'}";
}
}

Driver.java
=============
package com.cabbooking.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
public class Driver {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String contactNumber;
private String vehicleDetails;

// Constructors, getters, setters, toString, etc.

public Driver() {}

public Driver(String name, String contactNumber, String vehicleDetails) {


this.name = name;
this.contactNumber = contactNumber;
this.vehicleDetails = vehicleDetails;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getContactNumber() {


return contactNumber;
}

public void setContactNumber(String contactNumber) {


this.contactNumber = contactNumber;
}

public String getVehicleDetails() {


return vehicleDetails;
}

public void setVehicleDetails(String vehicleDetails) {


this.vehicleDetails = vehicleDetails;
}

@Override
public String toString() {
return "Driver{id=" + id + ", name='" + name + "', contactNumber='" +
contactNumber + "', vehicleDetails='" + vehicleDetails + "'}";
}
}

Booking.java
============
package com.cabbooking.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

@Entity
public class Booking {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
private Driver driver;

@OneToOne
private Payment payment;

private String customerName;


private String pickupLocation;
private String dropLocation;
private String status;

// Constructors, getters, setters, toString, etc.

public Booking() {}

public Booking(Driver driver, Payment payment, String customerName, String


pickupLocation, String dropLocation, String status) {
this.driver = driver;
this.payment = payment;
this.customerName = customerName;
this.pickupLocation = pickupLocation;
this.dropLocation = dropLocation;
this.status = status;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public Driver getDriver() {


return driver;
}

public void setDriver(Driver driver) {


this.driver = driver;
}

public Payment getPayment() {


return payment;
}
public void setPayment(Payment payment) {
this.payment = payment;
}

public String getCustomerName() {


return customerName;
}

public void setCustomerName(String customerName) {


this.customerName = customerName;
}

public String getPickupLocation() {


return pickupLocation;
}

public void setPickupLocation(String pickupLocation) {


this.pickupLocation = pickupLocation;
}

public String getDropLocation() {


return dropLocation;
}

public void setDropLocation(String dropLocation) {


this.dropLocation = dropLocation;
}

public String getStatus() {


return status;
}

public void setStatus(String status) {


this.status = status;
}

@Override
public String toString() {
return "Booking{id=" + id + ", driver=" + driver + ", payment=" + payment +
", customerName='" + customerName + "', pickupLocation='" + pickupLocation + "',
dropLocation='" + dropLocation + "', status='" + status + "'}";
}
}

Payment.java
=============
package com.cabbooking.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
public class Payment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double amount;
private String paymentMethod;
private String paymentStatus;

public Payment() {}

public Payment(Double amount, String paymentMethod, String paymentStatus) {


this.amount = amount;
this.paymentMethod = paymentMethod;
this.paymentStatus = paymentStatus;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public Double getAmount() {


return amount;
}

public void setAmount(Double amount) {


this.amount = amount;
}

public String getPaymentMethod() {


return paymentMethod;
}

public void setPaymentMethod(String paymentMethod) {


this.paymentMethod = paymentMethod;
}

public String getPaymentStatus() {


return paymentStatus;
}

public void setPaymentStatus(String paymentStatus) {


this.paymentStatus = paymentStatus;
}

@Override
public String toString() {
return "Payment{id=" + id + ", amount=" + amount + ", paymentMethod='" +
paymentMethod + "', paymentStatus='" + paymentStatus + "'}";
}
}

CustomException.java
======================
package com.cabbooking.exception;

public class CustomException extends Exception {

private String message;


private int errorCode;

public CustomException() {
super();
}

public CustomException(String message) {


super(message);
this.message = message;
}

public CustomException(String message, int errorCode) {


super(message);
this.message = message;
this.errorCode = errorCode;
}

public CustomException(String message, Throwable cause) {


super(message, cause);
this.message = message;
}

public CustomException(String message, int errorCode, Throwable cause) {


super(message, cause);
this.message = message;
this.errorCode = errorCode;
}

public String getMessage() {


return message;
}

public void setMessage(String message) {


this.message = message;
}

public int getErrorCode() {


return errorCode;
}

public void setErrorCode(int errorCode) {


this.errorCode = errorCode;
}

@Override
public String toString() {
return "CustomException{message='" + message + "', errorCode=" + errorCode
+ "}";
}
}

GlobalExceptionHandler.Java
============================

@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("Internal server error: " + ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}

UserRepository.java
====================

package com.cabbooking.repository;

import com.cabbooking.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {


Optional<User> findByEmail(String email);
}

DriverRepository.java
======================

package com.cabbooking.repository;

import com.cabbooking.entity.Driver;
import org.springframework.data.jpa.repository.JpaRepository;

public interface DriverRepository extends JpaRepository<Driver, Long> {


}

BookingRepository.java
=======================

package com.cabbooking.repository;

import com.cabbooking.entity.Booking;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookingRepository extends JpaRepository<Booking, Long> {


}

PaymentRepository.java
=====================
package com.cabbooking.repository;

import com.cabbooking.entity.Payment;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PaymentRepository extends JpaRepository<Payment, Long> {


}

UserService.java
================

package com.cabbooking.service;

import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;

public interface UserService {


User registerUser(UserDTO userDTO);

User getUserProfile(String email);


}

BookingService.java
===================

package com.cabbooking.service;

import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;

public interface BookingService {


Booking createBooking(BookingDTO bookingDTO);
}

PaymentService.java
===================

package com.cabbooking.service;

import com.cabbooking.entity.Payment;

public interface PaymentService {


Payment processPayment(Long bookingId, double amount);
}

UserServiceImpl.java
=====================

package com.cabbooking.service.impl;

import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.UserRepository;
import com.cabbooking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Autowired
private PasswordEncoder passwordEncoder;

@Override
public User registerUser(UserDTO userDTO) {
if (userRepository.findByEmail(userDTO.getEmail()).isPresent()) {
throw new CustomException("Email already exists");
}
User user = new User(userDTO.getName(), userDTO.getEmail(),
passwordEncoder.encode(userDTO.getPassword()), "USER");
return userRepository.save(user);
}

@Override
public User getUserProfile(String email) {
return userRepository.findByEmail(email).orElseThrow(() -> new
CustomException("User not found"));
}
}

BookingServiceImpl.java
=======================

package com.cabbooking.service.impl;

import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.repository.BookingRepository;
import com.cabbooking.service.BookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookingServiceImpl implements BookingService {

@Autowired
private BookingRepository bookingRepository;

@Override
public Booking createBooking(BookingDTO bookingDTO) {
Booking booking = new Booking();
booking.setUserId(bookingDTO.getUserId());
booking.setDriverId(bookingDTO.getDriverId());
booking.setPickupLocation(bookingDTO.getPickupLocation());
booking.setDropLocation(bookingDTO.getDropLocation());
booking.setBookingTime(bookingDTO.getBookingTime());
booking.setStatus("Pending");
return bookingRepository.save(booking);
}
}
PaymentService.java
====================

package com.cabbooking.service.impl;

import com.cabbooking.entity.Payment;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.BookingRepository;
import com.cabbooking.repository.PaymentRepository;
import com.cabbooking.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PaymentServiceImpl implements PaymentService {

@Autowired
private PaymentRepository paymentRepository;

@Autowired
private BookingRepository bookingRepository;

@Override
public Payment processPayment(Long bookingId, double amount) {
if (!bookingRepository.existsById(bookingId)) {
throw new CustomException("Booking not found");
}

Payment payment = new Payment();


payment.setBookingId(bookingId);
payment.setAmount(amount);
payment.setStatus("Completed");
return paymentRepository.save(payment);
}
}

JwtUtil.java
==============

package com.cabbooking.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class JwtUtil {

private final String SECRET_KEY = "cabbookingsecret";

public String generateToken(Authentication authentication) {


User user = (User) authentication.getPrincipal();
return Jwts.builder()
.setSubject(user.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60
* 10))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}

public boolean validateToken(String token) {


try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}

public String extractUsername(String token) {


return getClaims(token).getSubject();
}

public Claims getClaims(String token) {


return
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}

public String extractToken(HttpServletRequest request) {


String bearerToken = request.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}

application.properties
=======================

# Application Configurations
spring.application.name=cab-booking-app

# Server Configuration
server.port=8080

# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/cab_booking_db
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# JPA Properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

# JWT Configuration
jwt.secret=your_jwt_secret_key
jwt.expiration=3600000 # in milliseconds (1 hour)

# Logging Configuration
logging.level.org.springframework=INFO
logging.level.com.cabbooking=DEBUG
logging.file.name=logs/cab-booking-app.log

# Swagger Configuration (if applicable)


springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html

UserControllerTest.java
========================

package com.cabbooking.controller;

import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.service.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.Mockito.when;


import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.mockito.ArgumentMatchers.any;

@ExtendWith(MockitoExtension.class)
public class UserControllerTest {

private MockMvc mockMvc;

@Mock
private UserService userService;

@InjectMocks
private UserController userController;

@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
public void testRegisterUser() throws Exception {
UserDTO userDTO = new UserDTO("John", "[email protected]", "password123");
User user = new User(1L, "John", "[email protected]", "password123");

when(userService.registerUser(any(UserDTO.class))).thenReturn(user);

mockMvc.perform(post("/user/register")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"John\", \"email\":\"[email protected]\",
\"password\":\"password123\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}

@Test
public void testGetUserProfile() throws Exception {
User user = new User(1L, "John", "[email protected]", "password123");

when(userService.getUserProfile("[email protected]")).thenReturn(user);

mockMvc.perform(get("/user/profile").param("email", "[email protected]"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}
}

DriverControllerTest.java
=========================

package com.cabbooking.controller;

import com.cabbooking.entity.Driver;
import com.cabbooking.repository.DriverRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.Mockito.when;


import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.mockito.ArgumentMatchers.any;

@ExtendWith(MockitoExtension.class)
public class DriverControllerTest {

private MockMvc mockMvc;

@Mock
private DriverRepository driverRepository;

@InjectMocks
private DriverController driverController;

@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(driverController).build();
}

@Test
public void testRegisterDriver() throws Exception {
Driver driver = new Driver(1L, "Jane", "[email protected]", "car123");

when(driverRepository.save(any(Driver.class))).thenReturn(driver);

mockMvc.perform(post("/driver/register")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Jane\", \"email\":\"[email protected]\",
\"vehicle\":\"car123\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Jane"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}

@Test
public void testGetDriver() throws Exception {
Driver driver = new Driver(1L, "Jane", "[email protected]", "car123");

when(driverRepository.findById(1L)).thenReturn(java.util.Optional.of(driver));

mockMvc.perform(get("/driver/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Jane"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}
}

BookingControllerTest.java
===========================

package com.cabbooking.controller;

import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.service.BookingService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.Mockito.when;


import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.mockito.ArgumentMatchers.any;

@ExtendWith(MockitoExtension.class)
public class BookingControllerTest {

private MockMvc mockMvc;

@Mock
private BookingService bookingService;

@InjectMocks
private BookingController bookingController;

@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(bookingController).build();
}

@Test
public void testCreateBooking() throws Exception {
BookingDTO bookingDTO = new BookingDTO("John", "Jane", "car123",
"destination1");
Booking booking = new Booking(1L, "John", "Jane", "car123",
"destination1");

when(bookingService.createBooking(any(BookingDTO.class))).thenReturn(booking);

mockMvc.perform(post("/booking/create")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"user\":\"John\", \"driver\":\"Jane\", \"vehicl
e\":\"car123\", \"destination\":\"destination1\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user").value("John"))
.andExpect(jsonPath("$.driver").value("Jane"))
.andExpect(jsonPath("$.destination").value("destination1"));
}
}

PaymentControllerTest.java
===========================

package com.cabbooking.controller;

import com.cabbooking.entity.Payment;
import com.cabbooking.service.PaymentService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.Mockito.when;


import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static
org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.mockito.ArgumentMatchers.any;

@ExtendWith(MockitoExtension.class)
public class PaymentControllerTest {

private MockMvc mockMvc;

@Mock
private PaymentService paymentService;

@InjectMocks
private PaymentController paymentController;

@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(paymentController).build();
}

@Test
public void testProcessPayment() throws Exception {
Payment payment = new Payment(1L, 100.0, "Paid");

when(paymentService.processPayment(1L, 100.0)).thenReturn(payment);

mockMvc.perform(post("/payment/process")
.param("bookingId", "1")
.param("amount", "100.0"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("Paid"))
.andExpect(jsonPath("$.amount").value(100.0));
}
}

UserServiceImplTest.java
=========================

package com.cabbooking.service.impl;

import com.cabbooking.dto.UserDTO;
import com.cabbooking.entity.User;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;


import static org.mockito.Mockito.*;

public class UserServiceImplTest {

@Mock
private UserRepository userRepository;

@Mock
private PasswordEncoder passwordEncoder;

@InjectMocks
private UserServiceImpl userService;

private UserDTO userDTO;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
userDTO = new UserDTO("John Doe", "[email protected]", "password123");
}

@Test
public void testRegisterUser_ShouldReturnSavedUser() {

when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.empty());

when(passwordEncoder.encode(userDTO.getPassword())).thenReturn("encodedPassword");
when(userRepository.save(any(User.class))).thenReturn(new User("John Doe",
"[email protected]", "encodedPassword", "USER"));

User result = userService.registerUser(userDTO);

assertNotNull(result);
assertEquals("[email protected]", result.getEmail());
verify(userRepository, times(1)).save(any(User.class));
}

@Test
public void testRegisterUser_EmailAlreadyExists_ShouldThrowCustomException() {

when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.of(new
User()));

assertThrows(CustomException.class, () ->
userService.registerUser(userDTO));
}

@Test
public void testGetUserProfile_ShouldReturnUser() {

when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.of(new
User("John Doe", "[email protected]", "encodedPassword", "USER")));

User result = userService.getUserProfile(userDTO.getEmail());

assertNotNull(result);
assertEquals("[email protected]", result.getEmail());
}

@Test
public void testGetUserProfile_UserNotFound_ShouldThrowCustomException() {

when(userRepository.findByEmail(userDTO.getEmail())).thenReturn(Optional.empty());

assertThrows(CustomException.class, () ->
userService.getUserProfile(userDTO.getEmail()));
}
}

BookingServiceImplTest.java
============================

package com.cabbooking.service.impl;

import com.cabbooking.dto.BookingDTO;
import com.cabbooking.entity.Booking;
import com.cabbooking.repository.BookingRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.jupiter.api.Assertions.*;


import static org.mockito.Mockito.*;

public class BookingServiceImplTest {

@Mock
private BookingRepository bookingRepository;

@InjectMocks
private BookingServiceImpl bookingService;

private BookingDTO bookingDTO;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
bookingDTO = new BookingDTO(1L, 2L, "Location A", "Location B", "2024-12-11
10:00:00");
}

@Test
public void testCreateBooking_ShouldReturnSavedBooking() {

Booking booking = new Booking();


booking.setUserId(1L);
booking.setDriverId(2L);
booking.setPickupLocation("Location A");
booking.setDropLocation("Location B");
booking.setBookingTime("2024-12-11 10:00:00");
booking.setStatus("Pending");

when(bookingRepository.save(any(Booking.class))).thenReturn(booking);

Booking result = bookingService.createBooking(bookingDTO);

assertNotNull(result);
assertEquals("Location A", result.getPickupLocation());
assertEquals("Pending", result.getStatus());
verify(bookingRepository, times(1)).save(any(Booking.class));
}
}

PaymentServiceImplTest.java
============================

package com.cabbooking.service.impl;

import com.cabbooking.entity.Payment;
import com.cabbooking.exception.CustomException;
import com.cabbooking.repository.BookingRepository;
import com.cabbooking.repository.PaymentRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.jupiter.api.Assertions.*;


import static org.mockito.Mockito.*;

public class PaymentServiceImplTest {

@Mock
private PaymentRepository paymentRepository;

@Mock
private BookingRepository bookingRepository;

@InjectMocks
private PaymentServiceImpl paymentService;
private Long bookingId;
private double amount;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
bookingId = 1L;
amount = 100.0;
}

@Test
public void testProcessPayment_ShouldReturnProcessedPayment() {

when(bookingRepository.existsById(bookingId)).thenReturn(true);
Payment payment = new Payment();
payment.setBookingId(bookingId);
payment.setAmount(amount);
payment.setStatus("Completed");

when(paymentRepository.save(any(Payment.class))).thenReturn(payment);

Payment result = paymentService.processPayment(bookingId, amount);

assertNotNull(result);
assertEquals("Completed", result.getStatus());
verify(paymentRepository, times(1)).save(any(Payment.class));
}

@Test
public void testProcessPayment_BookingNotFound_ShouldThrowCustomException() {

when(bookingRepository.existsById(bookingId)).thenReturn(false);

assertThrows(CustomException.class, () ->
paymentService.processPayment(bookingId, amount));
}
}

FrontEnd Coding Structure


==========================

src
├── app
│ ├── auth
│ │ ├── login
│ │ │ ├── login.component.html
│ │ │ ├── login.component.ts
│ │ ├── register
│ │ ├── register.component.html
│ │ ├── register.component.ts
│ ├── user
│ │ ├── booking
│ │ │ ├── booking.component.html
│ │ │ ├── booking.component.ts
│ │ ├── profile
│ │ ├── profile.component.html
│ │ ├── profile.component.ts
│ ├── driver
│ │ ├── manage
│ │ ├── manage.component.html
│ │ ├── manage.component.ts
│ ├── admin
│ │ ├── dashboard
│ │ ├── dashboard.component.html
│ │ ├── dashboard.component.ts
│ ├── services
│ │ ├── auth.service.ts
│ │ ├── booking.service.ts
│ │ ├── user.service.ts
│ │ ├── driver.service.ts
│ ├── app-routing.module.ts
│ ├── app.module.ts
│ ├── app.component.html
│ ├── app.component.ts

app.component.html
==================

<div class="app-container">
<router-outlet></router-outlet>
</div>

app.module.ts
==============

import { NgModule } from '@angular/core';


import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { LoginComponent } from './auth/login/login.component';


import { RegisterComponent } from './auth/register/register.component';
import { BookingComponent } from './user/booking/booking.component';
import { ProfileComponent } from './user/profile/profile.component';
import { ManageComponent } from './driver/manage/manage.component';
import { DashboardComponent } from './admin/dashboard/dashboard.component';

import { HttpClientModule } from '@angular/common/http';


import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent,
BookingComponent,
ProfileComponent,
ManageComponent,
DashboardComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts
=====================

import { NgModule } from '@angular/core';


import { RouterModule, Routes } from '@angular/router';

import { LoginComponent } from './auth/login/login.component';


import { RegisterComponent } from './auth/register/register.component';
import { BookingComponent } from './user/booking/booking.component';
import { ProfileComponent } from './user/profile/profile.component';
import { ManageComponent } from './driver/manage/manage.component';
import { DashboardComponent } from './admin/dashboard/dashboard.component';

const routes: Routes = [


{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'user/booking', component: BookingComponent },
{ path: 'user/profile', component: ProfileComponent },
{ path: 'driver/manage', component: ManageComponent },
{ path: 'admin/dashboard', component: DashboardComponent },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Auth Module
============

auth.service.ts
================

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'https://localhost:8080/auth';

constructor(private http: HttpClient) {}


login(username: string, password: string): Observable<any> {
return this.http.post<any>(`${this.apiUrl}/login`, { username, password });
}

register(user: any): Observable<any> {


return this.http.post<any>(`${this.apiUrl}/register`, user);
}

getCurrentUser(): Observable<any> {
return this.http.get<any>(`${this.apiUrl}/currentUser`);
}

logout(): Observable<any> {
return this.http.post<any>(`${this.apiUrl}/logout`, {});
}
}

login.component.ts
==================

import { Component } from '@angular/core';


import { AuthService } from '../../auth.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
username: string = '';
password: string = '';

constructor(private authService: AuthService, private router: Router) {}

onLogin() {
this.authService.login(this.username, this.password).subscribe(
(response) => {
console.log('Login successful');
this.router.navigate(['/home']);
},
(error) => {
console.error('Login failed', error);
}
);
}
}

login.component.html
====================

<div class="login-form">
<h2>Login</h2>
<form (ngSubmit)="onLogin()">
<div>
<label for="username">Username</label>
<input type="text" id="username" [(ngModel)]="username" name="username"
required />
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" [(ngModel)]="password" name="password"
required />
</div>
<button type="submit" [disabled]="!username || !password">Login</button>
</form>
</div>

register.component.ts
=====================

import { Component } from '@angular/core';


import { AuthService } from '../../auth.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent {
username: string = '';
password: string = '';
email: string = '';

constructor(private authService: AuthService, private router: Router) {}

onRegister() {
const user = { username: this.username, password: this.password, email:
this.email };
this.authService.register(user).subscribe(
(response) => {
console.log('Registration successful');
this.router.navigate(['/login']);
},
(error) => {
console.error('Registration failed', error);
}
);
}
}

register.component.html
========================

<div class="register-form">
<h2>Register</h2>
<form (ngSubmit)="onRegister()">
<div>
<label for="username">Username</label>
<input type="text" id="username" [(ngModel)]="username" name="username"
required />
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" [(ngModel)]="password" name="password"
required />
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" [(ngModel)]="email" name="email" required />
</div>
<button type="submit" [disabled]="!username || !password ||
!email">Register</button>
</form>
</div>

User Module
===========

booking.component.html
=======================

<div class="booking-form">
<h2>Booking</h2>
<form (ngSubmit)="onBook()">
<div>
<label for="pickup">Pickup Location</label>
<input type="text" id="pickup" [(ngModel)]="pickupLocation"
name="pickupLocation" required />
</div>
<div>
<label for="destination">Destination</label>
<input type="text" id="destination" [(ngModel)]="destination"
name="destination" required />
</div>
<button type="submit" [disabled]="!pickupLocation ||
!destination">Book</button>
</form>
</div>

booking.component.ts
=====================

import { Component } from '@angular/core';


import { BookingService } from '../services/booking.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-booking',
templateUrl: './booking.component.html',
styleUrls: ['./booking.component.css']
})
export class BookingComponent {
pickupLocation: string = '';
destination: string = '';

constructor(private bookingService: BookingService, private router: Router) {}

onBook() {
const bookingDetails = { pickupLocation: this.pickupLocation, destination:
this.destination };
this.bookingService.createBooking(bookingDetails).subscribe(
(response) => {
console.log('Booking successful');
this.router.navigate(['/profile']);
},
(error) => {
console.error('Booking failed', error);
}
);
}
}

profile.component.html
======================

<div class="profile-details">
<h2>Your Profile</h2>

<!-- Display Profile Information -->


<div class="user-profile">
<h3>Profile Information</h3>
<p><strong>Name:</strong> {{ userDetails.name }}</p>
<p><strong>Email:</strong> {{ userDetails.email }}</p>
<p><strong>Phone:</strong> {{ userDetails.phone }}</p>
<p><strong>Address:</strong> {{ userDetails.address }}</p>
</div>

<!-- Display Booking History -->


<div class="booking-history">
<h3>Your Booking History</h3>
<table *ngIf="userDetails.bookings?.length > 0">
<thead>
<tr>
<th>Pickup Location</th>
<th>Destination</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let booking of userDetails.bookings">
<td>{{ booking.pickupLocation }}</td>
<td>{{ booking.destination }}</td>
<td>{{ booking.date | date: 'short' }}</td>
<td>{{ booking.status }}</td>
</tr>
</tbody>
</table>
<p *ngIf="userDetails.bookings?.length === 0">No bookings found.</p>
</div>
</div>
profile.component.ts
=====================

import { Component, OnInit } from '@angular/core';


import { UserService } from '../services/user.service';
import { Observable } from 'rxjs';

@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
userDetails: any = {};

constructor(private userService: UserService) {}

ngOnInit() {
this.fetchUserProfile();
}

fetchUserProfile() {
this.userService.getUserProfile().subscribe(
(data) => {
this.userDetails = data;
console.log('User Profile:', data);
},
(error) => {
console.error('Error fetching profile', error);
}
);
}
}

profile.component.css
=====================

.profile-details {
padding: 20px;
max-width: 800px;
margin: auto;
}

.user-profile, .booking-history {
margin-bottom: 20px;
}

h3 {
color: #333;
font-size: 1.2em;
}

table {
width: 100%;
border-collapse: collapse;
}

table th, table td {


padding: 10px;
text-align: left;
border: 1px solid #ddd;
}

table th {
background-color: #f4f4f4;
}

p {
font-size: 1em;
}

user.service.ts
==================

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'https://localhost:8080/user';

constructor(private http: HttpClient) {}

getUserProfile(userId: string): Observable<any> {


return this.http.get<any>(`${this.apiUrl}/profile/${userId}`);
}

updateUserProfile(userId: string, userData: any): Observable<any> {


return this.http.put<any>(`${this.apiUrl}/update/${userId}`, userData);
}
}

manage.component.html
=====================

<div class="manage-driver">
<h2>Manage Driver</h2>
<form (ngSubmit)="onManageDriver()">
<div>
<label for="driverId">Driver ID</label>
<input type="text" id="driverId" [(ngModel)]="driverId" name="driverId"
required />
</div>
<div>
<label for="status">Driver Status</label>
<select id="status" [(ngModel)]="status" name="status">
<option value="available">Available</option>
<option value="unavailable">Unavailable</option>
</select>
</div>
<button type="submit">Manage Driver</button>
</form>
</div>

manage.component.ts
===================

import { Component } from '@angular/core';


import { DriverService } from '../../services/driver.service';

@Component({
selector: 'app-manage',
templateUrl: './manage.component.html',
styleUrls: ['./manage.component.css']
})
export class ManageComponent {
driverId: string = '';
status: string = 'available';

constructor(private driverService: DriverService) {}

onManageDriver() {
const driverDetails = { driverId: this.driverId, status: this.status };
this.driverService.manageDriver(driverDetails).subscribe(
(response) => {
console.log('Driver status updated');
},
(error) => {
console.error('Error updating driver status', error);
}
);
}
}

dashboard.component.html
=========================

<div class="dashboard-container">
<h2>Admin Dashboard</h2>

<div class="statistics">
<div class="stat-card">
<h3>Total Bookings</h3>
<p>{{ totalBookings }}</p>
</div>

<div class="stat-card">
<h3>Active Users</h3>
<p>{{ activeUsers }}</p>
</div>

<div class="stat-card">
<h3>Total Drivers</h3>
<p>{{ totalDrivers }}</p>
</div>
</div>

<div class="recent-bookings">
<h3>Recent Bookings</h3>
<table *ngIf="recentBookings?.length > 0">
<thead>
<tr>
<th>Booking ID</th>
<th>Pickup Location</th>
<th>Destination</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let booking of recentBookings">
<td>{{ booking.bookingId }}</td>
<td>{{ booking.pickupLocation }}</td>
<td>{{ booking.destination }}</td>
<td>{{ booking.status }}</td>
</tr>
</tbody>
</table>
<p *ngIf="recentBookings?.length === 0">No recent bookings available.</p>
</div>
</div>

dashboard.component.ts
=======================

import { Component, OnInit } from '@angular/core';


import { AdminService } from '../services/admin.service';

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
totalBookings: number = 0;
activeUsers: number = 0;
totalDrivers: number = 0;
recentBookings: any[] = [];

constructor(private adminService: AdminService) {}

ngOnInit() {
this.loadDashboardData();
}

loadDashboardData() {
this.adminService.getDashboardData().subscribe(
(data) => {
this.totalBookings = data.totalBookings;
this.activeUsers = data.activeUsers;
this.totalDrivers = data.totalDrivers;
this.recentBookings = data.recentBookings;
},
(error) => {
console.error('Error loading dashboard data', error);
}
);
}
}

dashboard.component.css
=======================

.dashboard-container {
padding: 20px;
max-width: 900px;
margin: auto;
}

h2 {
color: #333;
text-align: center;
}

.statistics {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}

.stat-card {
background-color: #f4f4f4;
padding: 15px;
border-radius: 8px;
text-align: center;
width: 30%;
}

.stat-card h3 {
margin-bottom: 10px;
}

.recent-bookings table {
width: 100%;
border-collapse: collapse;
}

.recent-bookings th, .recent-bookings td {


padding: 10px;
text-align: left;
border: 1px solid #ddd;
}

.recent-bookings th {
background-color: #f4f4f4;
}
admin.service.ts
=================
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class AdminService {
private apiUrl = 'https://localhost:8080/admin';

constructor(private http: HttpClient) {}

getDashboardData(): Observable<any> {
return this.http.get<any>(`${this.apiUrl}/dashboard`);
}
}

booking.service.ts
===================

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class BookingService {
private apiUrl = 'https://localhost:8080/booking';

constructor(private http: HttpClient) {}

createBooking(booking: any): Observable<any> {


return this.http.post<any>(`${this.apiUrl}/create`, booking);
}

getAllBookings(): Observable<any[]> {
return this.http.get<any[]>(`${this.apiUrl}/all`);
}

getBookingById(bookingId: string): Observable<any> {


return this.http.get<any>(`${this.apiUrl}/get/${bookingId}`);
}
}

driver.service.ts
==================

import { Injectable } from '@angular/core';


import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DriverService {
private apiUrl = 'https://localhost:8080/driver';

constructor(private http: HttpClient) {}

getAllDrivers(): Observable<any[]> {
return this.http.get<any[]>(`${this.apiUrl}/all`);
}

getDriverById(driverId: string): Observable<any> {


return this.http.get<any>(`${this.apiUrl}/get/${driverId}`);
}

updateDriverDetails(driverId: string, driverData: any): Observable<any> {


return this.http.put<any>(`${this.apiUrl}/update/${driverId}`, driverData);
}
}

app.component.ts
=================

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Cab Booking System';
}

You might also like