mirror of
https://github.com/andwati/cymelle.git
synced 2026-11-30 03:28:45 +00:00
deploying
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
.env
|
||||
.gradle
|
||||
build
|
||||
out
|
||||
.idea
|
||||
*.iml
|
||||
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
@@ -0,0 +1,26 @@
|
||||
FROM eclipse-temurin:17-jdk-jammy AS build
|
||||
|
||||
WORKDIR /workspace
|
||||
|
||||
COPY gradlew settings.gradle.kts build.gradle.kts ./
|
||||
COPY gradle ./gradle
|
||||
COPY src ./src
|
||||
|
||||
RUN chmod +x ./gradlew && ./gradlew --no-daemon bootJar -x test
|
||||
|
||||
FROM eclipse-temurin:17-jre-jammy
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN groupadd --system app && useradd --system --gid app app
|
||||
|
||||
COPY --from=build /workspace/build/libs/*.jar /app/app.jar
|
||||
COPY docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
if [ -z "${DATABASE_URL:-}" ] && [ -n "${NEON_DATABASE_URL:-}" ]; then
|
||||
DATABASE_URL="$NEON_DATABASE_URL"
|
||||
export DATABASE_URL
|
||||
fi
|
||||
|
||||
case "${DATABASE_URL:-}" in
|
||||
jdbc:postgresql://*)
|
||||
export SPRING_DATASOURCE_URL="${SPRING_DATASOURCE_URL:-$DATABASE_URL}"
|
||||
;;
|
||||
postgres://*|postgresql://*)
|
||||
raw_url="${DATABASE_URL#postgres://}"
|
||||
raw_url="${raw_url#postgresql://}"
|
||||
|
||||
if [ "$raw_url" != "${raw_url#*@}" ]; then
|
||||
credentials="${raw_url%%@*}"
|
||||
host_and_database="${raw_url#*@}"
|
||||
|
||||
if [ -z "${SPRING_DATASOURCE_USERNAME:-}" ]; then
|
||||
export SPRING_DATASOURCE_USERNAME="${credentials%%:*}"
|
||||
fi
|
||||
|
||||
if [ -z "${SPRING_DATASOURCE_PASSWORD:-}" ] && [ "$credentials" != "${credentials#*:}" ]; then
|
||||
export SPRING_DATASOURCE_PASSWORD="${credentials#*:}"
|
||||
fi
|
||||
else
|
||||
host_and_database="$raw_url"
|
||||
fi
|
||||
|
||||
export SPRING_DATASOURCE_URL="${SPRING_DATASOURCE_URL:-jdbc:postgresql://$host_and_database}"
|
||||
;;
|
||||
esac
|
||||
|
||||
exec java ${JAVA_OPTS:-} -jar /app/app.jar
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
|
||||
networkTimeout=10000
|
||||
retries=0
|
||||
retryBackOffMs=500
|
||||
networkTimeout=60000
|
||||
retries=3
|
||||
retryBackOffMs=1000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.andwati.orders.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
@@ -8,16 +9,24 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
@Value("${app.cors.allowed-origins:http://localhost:3000}")
|
||||
private String allowedOrigins;
|
||||
|
||||
@Bean
|
||||
WebMvcConfigurer corsConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/api/**")
|
||||
.allowedOrigins("http://localhost:3000")
|
||||
.allowedOrigins(parseAllowedOrigins())
|
||||
.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS")
|
||||
.allowedHeaders("*");
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private String[] parseAllowedOrigins() {
|
||||
return allowedOrigins.split("\\s*,\\s*");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@ package com.andwati.orders.config;
|
||||
|
||||
|
||||
import com.andwati.orders.model.*;
|
||||
import com.andwati.orders.repository.AppUserRepository;
|
||||
import com.andwati.orders.repository.InventoryItemRepository;
|
||||
import com.andwati.orders.repository.OrderRepository;
|
||||
import com.andwati.orders.repository.ProductRepository;
|
||||
import com.andwati.orders.repository.RideRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
@@ -19,6 +22,9 @@ public class DataSeeder implements CommandLineRunner {
|
||||
private final ProductRepository productRepository;
|
||||
private final InventoryItemRepository inventoryItemRepository;
|
||||
private final OrderRepository orderRepository;
|
||||
private final RideRepository rideRepository;
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final boolean seedData;
|
||||
|
||||
|
||||
@@ -26,97 +32,90 @@ public class DataSeeder implements CommandLineRunner {
|
||||
ProductRepository productRepository,
|
||||
InventoryItemRepository inventoryItemRepository,
|
||||
OrderRepository orderRepository,
|
||||
RideRepository rideRepository,
|
||||
AppUserRepository appUserRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
@Value("${app.seed-data:true}") boolean seedData
|
||||
) {
|
||||
this.productRepository = productRepository;
|
||||
this.inventoryItemRepository = inventoryItemRepository;
|
||||
this.orderRepository = orderRepository;
|
||||
this.rideRepository = rideRepository;
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.seedData = seedData;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) {
|
||||
if (!seedData || productRepository.count() > 0) {
|
||||
if (!seedData) {
|
||||
return;
|
||||
}
|
||||
|
||||
AppUser admin = ensureUser("admin", "Admin User", "admin123", Role.ADMIN);
|
||||
AppUser driver = ensureUser("driver", "Demo Driver", "driver123", Role.DRIVER);
|
||||
AppUser driverTwo = ensureUser("driver2", "Amina Driver", "driver123", Role.DRIVER);
|
||||
AppUser driverThree = ensureUser("driver3", "Otieno Driver", "driver123", Role.DRIVER);
|
||||
AppUser customer = ensureUser("customer", "Demo Customer", "customer123", Role.CUSTOMER);
|
||||
AppUser customerTwo = ensureUser("customer2", "Nia Customer", "customer123", Role.CUSTOMER);
|
||||
AppUser customerThree = ensureUser("customer3", "Baraka Customer", "customer123", Role.CUSTOMER);
|
||||
AppUser customerFour = ensureUser("customer4", "Wanjiku Customer", "customer123", Role.CUSTOMER);
|
||||
|
||||
Product mouse = product("Wireless Mouse", "MOUSE-001", "1500.00");
|
||||
Product keyboard = product("Keyboard", "KEYBOARD-001", "2500.00");
|
||||
Product cable = product("USB-C Cable", "USB-C-001", "800.00");
|
||||
Product stand = product("Laptop Stand", "STAND-001", "3500.00");
|
||||
Product webcam = product("Webcam", "WEBCAM-001", "4500.00");
|
||||
Product mouse = ensureProduct("Wireless Mouse", "MOUSE-001", "1500.00", 18, 5);
|
||||
Product keyboard = ensureProduct("Mechanical Keyboard", "KEYBOARD-001", "4500.00", 9, 4);
|
||||
Product cable = ensureProduct("USB-C Cable", "USB-C-001", "800.00", 32, 10);
|
||||
Product stand = ensureProduct("Laptop Stand", "STAND-001", "3500.00", 7, 5);
|
||||
Product webcam = ensureProduct("Webcam", "WEBCAM-001", "4500.00", 4, 5);
|
||||
Product headphones = ensureProduct("Noise Cancelling Headphones", "AUDIO-001", "12500.00", 11, 3);
|
||||
Product monitor = ensureProduct("27 Inch Monitor", "MONITOR-001", "28500.00", 6, 2);
|
||||
Product dock = ensureProduct("USB-C Docking Station", "DOCK-001", "9200.00", 5, 3);
|
||||
Product backpack = ensureProduct("Commuter Laptop Backpack", "BAG-001", "6200.00", 15, 6);
|
||||
Product powerBank = ensureProduct("Fast Charge Power Bank", "POWER-001", "5400.00", 12, 4);
|
||||
Product tablet = ensureProduct("Drawing Tablet", "TABLET-001", "16900.00", 3, 3);
|
||||
Product chair = ensureProduct("Ergonomic Office Chair", "CHAIR-001", "24500.00", 2, 2);
|
||||
|
||||
productRepository.saveAll(List.of(mouse, keyboard, cable, stand, webcam));
|
||||
if (orderRepository.count() < 14) {
|
||||
seedActivity(
|
||||
List.of(customer, customerTwo, customerThree, customerFour),
|
||||
List.of(driver, driverTwo, driverThree),
|
||||
List.of(mouse, keyboard, cable, stand, webcam, headphones, monitor, dock, backpack, powerBank, tablet, chair)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
inventoryItemRepository.saveAll(List.of(
|
||||
inventory(mouse, 12, 5),
|
||||
inventory(keyboard, 3, 5),
|
||||
inventory(cable, 0, 5),
|
||||
inventory(stand, 7, 5),
|
||||
inventory(webcam, 2, 5)
|
||||
));
|
||||
Order placedOrder = new Order();
|
||||
placedOrder.setCustomerName("Demo Customer");
|
||||
placedOrder.setStatus(OrderStatus.PLACED);
|
||||
placedOrder.setCurrency("KES");
|
||||
placedOrder.setCreatedAt(Instant.now().minusSeconds(3600));
|
||||
|
||||
OrderItem itemOne = new OrderItem();
|
||||
itemOne.setOrder(placedOrder);
|
||||
itemOne.setProduct(mouse);
|
||||
itemOne.setProductName(mouse.getName());
|
||||
itemOne.setQuantity(1);
|
||||
itemOne.setUnitPrice(mouse.getPrice());
|
||||
itemOne.setLineTotal(mouse.getPrice());
|
||||
|
||||
OrderItem itemTwo = new OrderItem();
|
||||
itemTwo.setOrder(placedOrder);
|
||||
itemTwo.setProduct(keyboard);
|
||||
itemTwo.setProductName(keyboard.getName());
|
||||
itemTwo.setQuantity(1);
|
||||
itemTwo.setUnitPrice(keyboard.getPrice());
|
||||
itemTwo.setLineTotal(keyboard.getPrice());
|
||||
|
||||
placedOrder.addItem(itemOne);
|
||||
placedOrder.addItem(itemTwo);
|
||||
placedOrder.recalculateTotal();
|
||||
|
||||
Order cancelledOrder = new Order();
|
||||
cancelledOrder.setCustomerName("Cancelled Customer");
|
||||
cancelledOrder.setStatus(OrderStatus.CANCELLED);
|
||||
cancelledOrder.setCurrency("KES");
|
||||
cancelledOrder.setCreatedAt(Instant.now().minusSeconds(86_400));
|
||||
cancelledOrder.setCancelledAt(Instant.now().minusSeconds(80_000));
|
||||
|
||||
OrderItem cancelledItem = new OrderItem();
|
||||
cancelledItem.setOrder(cancelledOrder);
|
||||
cancelledItem.setProduct(webcam);
|
||||
cancelledItem.setProductName(webcam.getName());
|
||||
cancelledItem.setQuantity(1);
|
||||
cancelledItem.setUnitPrice(webcam.getPrice());
|
||||
cancelledItem.setLineTotal(webcam.getPrice());
|
||||
|
||||
cancelledOrder.addItem(cancelledItem);
|
||||
cancelledOrder.recalculateTotal();
|
||||
|
||||
orderRepository.saveAll(List.of(placedOrder, cancelledOrder));
|
||||
private AppUser ensureUser(String username, String displayName, String password, Role role) {
|
||||
return appUserRepository.findByUsernameIgnoreCase(username)
|
||||
.orElseGet(() -> appUserRepository.save(new AppUser()
|
||||
.setUsername(username)
|
||||
.setDisplayName(displayName)
|
||||
.setPasswordHash(passwordEncoder.encode(password))
|
||||
.setRole(role)
|
||||
.setEnabled(true)));
|
||||
}
|
||||
|
||||
|
||||
private Product product(String name, String sku, String price) {
|
||||
Product product = new Product();
|
||||
product.setName(name);
|
||||
product.setSku(sku);
|
||||
product.setPrice(new BigDecimal(price));
|
||||
product.setCurrency("KES");
|
||||
product.setActive(true);
|
||||
product.setCreatedAt(Instant.now());
|
||||
product.setUpdatedAt(Instant.now());
|
||||
private Product ensureProduct(String name, String sku, String price, int availableQuantity, int reorderLevel) {
|
||||
Product product = productRepository.findBySkuIgnoreCase(sku)
|
||||
.orElseGet(() -> productRepository.save(product(name, sku, price)));
|
||||
|
||||
inventoryItemRepository.findByProduct_Id(product.getId())
|
||||
.orElseGet(() -> inventoryItemRepository.save(inventory(product, availableQuantity, reorderLevel)));
|
||||
|
||||
return product;
|
||||
}
|
||||
|
||||
private Product product(String name, String sku, String price) {
|
||||
return new Product()
|
||||
.setName(name)
|
||||
.setSku(sku)
|
||||
.setPrice(new BigDecimal(price))
|
||||
.setCurrency("KES")
|
||||
.setActive(true)
|
||||
.setCreatedAt(Instant.now())
|
||||
.setUpdatedAt(Instant.now());
|
||||
}
|
||||
|
||||
private InventoryItem inventory(Product product, int availableQuantity, int reorderLevel) {
|
||||
InventoryItem inventoryItem = new InventoryItem();
|
||||
inventoryItem.setProduct(product);
|
||||
@@ -126,4 +125,102 @@ public class DataSeeder implements CommandLineRunner {
|
||||
inventoryItem.setUpdatedAt(Instant.now());
|
||||
return inventoryItem;
|
||||
}
|
||||
|
||||
private void seedActivity(List<AppUser> customers, List<AppUser> drivers, List<Product> products) {
|
||||
Instant now = Instant.now();
|
||||
List<Order> orders = List.of(
|
||||
order(customers.get(0), OrderStatus.PENDING, now.minusSeconds(2_400), line(products.get(0), 1), line(products.get(2), 2)),
|
||||
order(customers.get(1), OrderStatus.PENDING, now.minusSeconds(7_200), line(products.get(8), 1), line(products.get(9), 1)),
|
||||
order(customers.get(2), OrderStatus.SHIPPED, now.minusSeconds(26_000), line(products.get(1), 1), line(products.get(3), 1)),
|
||||
order(customers.get(3), OrderStatus.SHIPPED, now.minusSeconds(44_000), line(products.get(5), 1)),
|
||||
order(customers.get(0), OrderStatus.DELIVERED, now.minusSeconds(91_000), line(products.get(6), 1), line(products.get(2), 3)),
|
||||
order(customers.get(1), OrderStatus.DELIVERED, now.minusSeconds(130_000), line(products.get(7), 1), line(products.get(0), 1)),
|
||||
order(customers.get(2), OrderStatus.DELIVERED, now.minusSeconds(185_000), line(products.get(10), 1), line(products.get(2), 1)),
|
||||
order(customers.get(3), OrderStatus.DELIVERED, now.minusSeconds(252_000), line(products.get(11), 1)),
|
||||
order(customers.get(0), OrderStatus.CANCELLED, now.minusSeconds(316_000), line(products.get(4), 1)),
|
||||
order(customers.get(1), OrderStatus.PENDING, now.minusSeconds(374_000), line(products.get(3), 1), line(products.get(9), 2)),
|
||||
order(customers.get(2), OrderStatus.SHIPPED, now.minusSeconds(442_000), line(products.get(5), 1), line(products.get(8), 1)),
|
||||
order(customers.get(3), OrderStatus.DELIVERED, now.minusSeconds(518_000), line(products.get(6), 1), line(products.get(1), 1))
|
||||
);
|
||||
orderRepository.saveAll(orders);
|
||||
|
||||
rideRepository.saveAll(List.of(
|
||||
ride(orders.get(0), null, RideStatus.REQUESTED, "Westlands warehouse", "Kilimani, Nairobi", "7.20", null, now.minusSeconds(2_100)),
|
||||
ride(orders.get(1), null, RideStatus.REQUESTED, "Mombasa Road hub", "Syokimau", "11.50", null, now.minusSeconds(6_800)),
|
||||
ride(orders.get(2), drivers.get(0), RideStatus.ACCEPTED, "CBD pickup", "Lavington", "6.30", "950.00", now.minusSeconds(24_000)),
|
||||
ride(orders.get(3), drivers.get(1), RideStatus.ACCEPTED, "Industrial Area", "Kileleshwa", "8.40", "1180.00", now.minusSeconds(42_000)),
|
||||
ride(orders.get(4), drivers.get(0), RideStatus.COMPLETED, "Thika Road hub", "Roysambu", "13.10", "1580.00", now.minusSeconds(88_000)),
|
||||
ride(orders.get(5), drivers.get(2), RideStatus.COMPLETED, "Karen store", "Langata", "5.80", "870.00", now.minusSeconds(128_000)),
|
||||
ride(orders.get(6), drivers.get(1), RideStatus.COMPLETED, "Westlands warehouse", "Parklands", "4.60", "760.00", now.minusSeconds(182_000)),
|
||||
ride(orders.get(8), null, RideStatus.CANCELLED, "CBD pickup", "Upper Hill", "3.90", null, now.minusSeconds(314_000)),
|
||||
ride(orders.get(10), drivers.get(2), RideStatus.ACCEPTED, "Mombasa Road hub", "Athi River", "18.50", "2140.00", now.minusSeconds(438_000)),
|
||||
ride(orders.get(11), drivers.get(0), RideStatus.COMPLETED, "Industrial Area", "Embakasi", "9.20", "1240.00", now.minusSeconds(514_000))
|
||||
));
|
||||
}
|
||||
|
||||
private Order order(AppUser customer, OrderStatus status, Instant createdAt, SeedLine... lines) {
|
||||
Order order = new Order()
|
||||
.setCustomer(customer)
|
||||
.setCustomerName(customer.getDisplayName())
|
||||
.setStatus(status)
|
||||
.setCurrency("KES")
|
||||
.setCreatedAt(createdAt);
|
||||
|
||||
if (status == OrderStatus.CANCELLED) {
|
||||
order.setCancelledAt(createdAt.plusSeconds(900));
|
||||
}
|
||||
|
||||
for (SeedLine line : lines) {
|
||||
order.addItem(OrderItem.from(line.product(), line.quantity()));
|
||||
}
|
||||
|
||||
order.recalculateTotal();
|
||||
return order;
|
||||
}
|
||||
|
||||
private Ride ride(
|
||||
Order order,
|
||||
AppUser driver,
|
||||
RideStatus status,
|
||||
String pickup,
|
||||
String dropoff,
|
||||
String distanceKm,
|
||||
String fareAmount,
|
||||
Instant requestedAt
|
||||
) {
|
||||
Ride ride = new Ride()
|
||||
.setOrder(order)
|
||||
.setCustomer(order.getCustomer())
|
||||
.setDriver(driver)
|
||||
.setPickupLocation(pickup)
|
||||
.setDropoffLocation(dropoff)
|
||||
.setDistanceKm(new BigDecimal(distanceKm))
|
||||
.setStatus(status)
|
||||
.setRequestedAt(requestedAt);
|
||||
|
||||
if (fareAmount != null) {
|
||||
ride.setFareAmount(new BigDecimal(fareAmount)).setCurrency("KES");
|
||||
}
|
||||
|
||||
if (status == RideStatus.ACCEPTED || status == RideStatus.COMPLETED) {
|
||||
ride.setAcceptedAt(requestedAt.plusSeconds(1_200));
|
||||
}
|
||||
|
||||
if (status == RideStatus.COMPLETED) {
|
||||
ride.setCompletedAt(requestedAt.plusSeconds(7_200));
|
||||
}
|
||||
|
||||
if (status == RideStatus.CANCELLED) {
|
||||
ride.setCancelledAt(requestedAt.plusSeconds(1_800));
|
||||
}
|
||||
|
||||
return ride;
|
||||
}
|
||||
|
||||
private SeedLine line(Product product, int quantity) {
|
||||
return new SeedLine(product, quantity);
|
||||
}
|
||||
|
||||
private record SeedLine(Product product, int quantity) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.andwati.orders.config;
|
||||
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class OrderStatusMigrator implements CommandLineRunner {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public OrderStatusMigrator(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
try {
|
||||
jdbcTemplate.update("alter table orders drop constraint if exists orders_status_check");
|
||||
jdbcTemplate.update("update orders set status = 'PENDING' where status = 'PLACED'");
|
||||
} catch (RuntimeException ignored) {
|
||||
// The table may not exist yet during first boot with hibernate ddl-auto=update.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.andwati.orders.config;
|
||||
|
||||
import com.andwati.orders.services.AppUserDetailsService;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
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.csrf.CookieCsrfTokenRepository;
|
||||
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
CsrfTokenRequestAttributeHandler csrfRequestHandler = new CsrfTokenRequestAttributeHandler();
|
||||
csrfRequestHandler.setCsrfRequestAttributeName(null);
|
||||
|
||||
return http
|
||||
.cors(Customizer.withDefaults())
|
||||
.csrf(csrf -> csrf
|
||||
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
|
||||
.csrfTokenRequestHandler(csrfRequestHandler)
|
||||
)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.logout(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(HttpMethod.GET, "/api/health", "/api/auth/csrf").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/auth/login", "/api/auth/register").permitAll()
|
||||
.requestMatchers("/api-docs/**", "/swagger-ui.html", "/swagger-ui/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/products/**").hasRole("ADMIN")
|
||||
.requestMatchers(HttpMethod.PUT, "/api/products/**").hasRole("ADMIN")
|
||||
.requestMatchers(HttpMethod.PATCH, "/api/products/**").hasRole("ADMIN")
|
||||
.requestMatchers(HttpMethod.DELETE, "/api/products/**").hasRole("ADMIN")
|
||||
.requestMatchers("/api/inventory/**").hasRole("ADMIN")
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DaoAuthenticationProvider authenticationProvider(
|
||||
AppUserDetailsService appUserDetailsService,
|
||||
PasswordEncoder passwordEncoder
|
||||
) {
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(appUserDetailsService);
|
||||
provider.setPasswordEncoder(passwordEncoder);
|
||||
return provider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
|
||||
return configuration.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.andwati.orders.controller;
|
||||
|
||||
import com.andwati.orders.dto.request.LoginRequest;
|
||||
import com.andwati.orders.dto.request.RegisterRequest;
|
||||
import com.andwati.orders.dto.response.AuthUserResponse;
|
||||
import com.andwati.orders.dto.response.CsrfResponse;
|
||||
import com.andwati.orders.services.AppUserService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final AppUserService appUserService;
|
||||
|
||||
public AuthController(AuthenticationManager authenticationManager, AppUserService appUserService) {
|
||||
this.authenticationManager = authenticationManager;
|
||||
this.appUserService = appUserService;
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public AuthUserResponse register(@Valid @RequestBody RegisterRequest request) {
|
||||
return appUserService.registerCustomer(request);
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public AuthUserResponse login(@Valid @RequestBody LoginRequest request, HttpServletRequest servletRequest) {
|
||||
var authentication = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
appUserService.normalizeUsername(request.username()),
|
||||
request.password()
|
||||
)
|
||||
);
|
||||
|
||||
var context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(authentication);
|
||||
SecurityContextHolder.setContext(context);
|
||||
|
||||
servletRequest.getSession(true).setAttribute(
|
||||
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
|
||||
context
|
||||
);
|
||||
|
||||
return me();
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
public void logout(HttpServletRequest request) {
|
||||
SecurityContextHolder.clearContext();
|
||||
HttpSession session = request.getSession(false);
|
||||
|
||||
if (session != null) {
|
||||
session.invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public AuthUserResponse me() {
|
||||
return appUserService.toResponse(appUserService.getCurrentUser());
|
||||
}
|
||||
|
||||
@GetMapping("/csrf")
|
||||
public CsrfResponse csrf(CsrfToken csrfToken) {
|
||||
return new CsrfResponse(
|
||||
csrfToken.getHeaderName(),
|
||||
csrfToken.getParameterName(),
|
||||
csrfToken.getToken()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.andwati.orders.controller;
|
||||
|
||||
import com.andwati.orders.dto.request.CreateOrderRequest;
|
||||
import com.andwati.orders.dto.request.UpdateOrderStatusRequest;
|
||||
import com.andwati.orders.dto.response.CancelOrderResponse;
|
||||
import com.andwati.orders.dto.response.OrderResponse;
|
||||
import com.andwati.orders.dto.response.OrderSummaryResponse;
|
||||
@@ -51,7 +52,7 @@ public class OrderController {
|
||||
)
|
||||
@GetMapping
|
||||
public PageResponse<OrderSummaryResponse> listOrders(
|
||||
@Parameter(description = "Optional order status filter.", example = "PLACED")
|
||||
@Parameter(description = "Optional order status filter.", example = "PENDING")
|
||||
@RequestParam(required = false) OrderStatus status,
|
||||
|
||||
@Parameter(
|
||||
@@ -107,4 +108,13 @@ public class OrderController {
|
||||
) {
|
||||
return orderService.cancelOrder(id);
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}/status")
|
||||
public OrderResponse updateStatus(
|
||||
@Parameter(description = "Order ID.", example = "11111111-1111-1111-1111-111111111111")
|
||||
@PathVariable UUID id,
|
||||
@Valid @RequestBody UpdateOrderStatusRequest request
|
||||
) {
|
||||
return orderService.updateStatus(id, request.status());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.andwati.orders.controller;
|
||||
|
||||
import com.andwati.orders.dto.request.ProductRequest;
|
||||
import com.andwati.orders.dto.response.ProductResponse;
|
||||
import com.andwati.orders.services.ProductService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/products")
|
||||
public class ProductController {
|
||||
|
||||
private final ProductService productService;
|
||||
|
||||
public ProductController(ProductService productService) {
|
||||
this.productService = productService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<ProductResponse> listProducts() {
|
||||
return productService.listProducts();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ProductResponse getProduct(@PathVariable UUID id) {
|
||||
return productService.getProduct(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public ProductResponse createProduct(@Valid @RequestBody ProductRequest request) {
|
||||
return productService.createProduct(request);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ProductResponse updateProduct(@PathVariable UUID id, @Valid @RequestBody ProductRequest request) {
|
||||
return productService.updateProduct(id, request);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ProductResponse deactivateProduct(@PathVariable UUID id) {
|
||||
return productService.deactivateProduct(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.andwati.orders.controller;
|
||||
|
||||
import com.andwati.orders.dto.request.CreateRideRequest;
|
||||
import com.andwati.orders.dto.request.UpdateRideStatusRequest;
|
||||
import com.andwati.orders.dto.response.RideResponse;
|
||||
import com.andwati.orders.services.RideService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/rides")
|
||||
public class RideController {
|
||||
|
||||
private final RideService rideService;
|
||||
|
||||
public RideController(RideService rideService) {
|
||||
this.rideService = rideService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<RideResponse> listRides() {
|
||||
return rideService.listRides();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public RideResponse requestRide(@Valid @RequestBody CreateRideRequest request) {
|
||||
return rideService.requestRide(request);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/accept")
|
||||
public RideResponse acceptRide(@PathVariable UUID id) {
|
||||
return rideService.acceptRide(id);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/complete")
|
||||
public RideResponse completeRide(@PathVariable UUID id) {
|
||||
return rideService.completeRide(id);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public RideResponse cancelRide(@PathVariable UUID id) {
|
||||
return rideService.cancelRide(id);
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}/status")
|
||||
public RideResponse updateStatus(
|
||||
@PathVariable UUID id,
|
||||
@Valid @RequestBody UpdateRideStatusRequest request
|
||||
) {
|
||||
return rideService.updateStatus(id, request.status());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.andwati.orders.controller;
|
||||
|
||||
import com.andwati.orders.dto.request.AdminUserRequest;
|
||||
import com.andwati.orders.dto.response.UserResponse;
|
||||
import com.andwati.orders.services.AppUserService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/users")
|
||||
public class UserController {
|
||||
|
||||
private final AppUserService appUserService;
|
||||
|
||||
public UserController(AppUserService appUserService) {
|
||||
this.appUserService = appUserService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public List<UserResponse> listUsers() {
|
||||
return appUserService.listUsers();
|
||||
}
|
||||
|
||||
@GetMapping("/customers")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public List<UserResponse> listCustomers() {
|
||||
return appUserService.listCustomers();
|
||||
}
|
||||
|
||||
@GetMapping("/drivers")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public List<UserResponse> listDrivers() {
|
||||
return appUserService.listDrivers();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public UserResponse createUser(@Valid @RequestBody AdminUserRequest request) {
|
||||
return appUserService.createUser(request);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public UserResponse updateUser(@PathVariable UUID id, @Valid @RequestBody AdminUserRequest request) {
|
||||
return appUserService.updateUser(id, request);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public UserResponse disableUser(@PathVariable UUID id) {
|
||||
return appUserService.disableUser(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import com.andwati.orders.model.Role;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record AdminUserRequest(
|
||||
@NotBlank(message = "username is required")
|
||||
@Size(max = 80, message = "username must be 80 characters or fewer")
|
||||
String username,
|
||||
|
||||
@NotBlank(message = "displayName is required")
|
||||
@Size(max = 120, message = "displayName must be 120 characters or fewer")
|
||||
String displayName,
|
||||
|
||||
@Size(min = 6, max = 120, message = "password must be between 6 and 120 characters")
|
||||
String password,
|
||||
|
||||
@NotNull(message = "role is required")
|
||||
Role role,
|
||||
|
||||
boolean enabled
|
||||
) {
|
||||
}
|
||||
@@ -1,18 +1,16 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record CreateOrderRequest(
|
||||
@NotBlank(message = "customerName is required")
|
||||
@Size(min = 2, max = 120, message = "customerName must be between 2 and 120 characters")
|
||||
String customerName,
|
||||
|
||||
@Valid
|
||||
@Size(min = 1, message = "items must contain at least one item")
|
||||
List<CreateOrderItemRequest> items
|
||||
List<CreateOrderItemRequest> items,
|
||||
|
||||
@Valid
|
||||
CreateOrderRideRequest deliveryRide
|
||||
) {
|
||||
}
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public record CreateOrderRideRequest(
|
||||
@NotBlank(message = "pickupLocation is required")
|
||||
@Size(max = 160, message = "pickupLocation must be 160 characters or fewer")
|
||||
String pickupLocation,
|
||||
|
||||
@NotBlank(message = "dropoffLocation is required")
|
||||
@Size(max = 160, message = "dropoffLocation must be 160 characters or fewer")
|
||||
String dropoffLocation,
|
||||
|
||||
@NotNull(message = "distanceKm is required")
|
||||
@DecimalMin(value = "0.1", message = "distanceKm must be greater than 0")
|
||||
BigDecimal distanceKm
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
public record CreateRideRequest(
|
||||
@NotNull(message = "orderId is required")
|
||||
UUID orderId,
|
||||
|
||||
@NotBlank(message = "pickupLocation is required")
|
||||
@Size(max = 160, message = "pickupLocation must be 160 characters or fewer")
|
||||
String pickupLocation,
|
||||
|
||||
@NotBlank(message = "dropoffLocation is required")
|
||||
@Size(max = 160, message = "dropoffLocation must be 160 characters or fewer")
|
||||
String dropoffLocation,
|
||||
|
||||
@NotNull(message = "distanceKm is required")
|
||||
@DecimalMin(value = "0.1", message = "distanceKm must be greater than 0")
|
||||
BigDecimal distanceKm
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record LoginRequest(
|
||||
@NotBlank(message = "username is required")
|
||||
String username,
|
||||
|
||||
@NotBlank(message = "password is required")
|
||||
String password
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public record ProductRequest(
|
||||
@NotBlank(message = "name is required")
|
||||
@Size(max = 120, message = "name must be 120 characters or fewer")
|
||||
String name,
|
||||
|
||||
@NotBlank(message = "sku is required")
|
||||
@Size(max = 80, message = "sku must be 80 characters or fewer")
|
||||
String sku,
|
||||
|
||||
@NotNull(message = "price is required")
|
||||
@DecimalMin(value = "0.01", message = "price must be greater than 0")
|
||||
BigDecimal price,
|
||||
|
||||
@NotBlank(message = "currency is required")
|
||||
@Size(min = 3, max = 3, message = "currency must be a 3-letter code")
|
||||
String currency,
|
||||
|
||||
boolean active,
|
||||
|
||||
@Min(value = 0, message = "availableQuantity must be greater than or equal to 0")
|
||||
int availableQuantity,
|
||||
|
||||
@Min(value = 0, message = "reorderLevel must be greater than or equal to 0")
|
||||
int reorderLevel
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record RegisterRequest(
|
||||
@NotBlank(message = "username is required")
|
||||
@Size(min = 3, max = 80, message = "username must be between 3 and 80 characters")
|
||||
String username,
|
||||
|
||||
@NotBlank(message = "displayName is required")
|
||||
@Size(min = 2, max = 120, message = "displayName must be between 2 and 120 characters")
|
||||
String displayName,
|
||||
|
||||
@NotBlank(message = "password is required")
|
||||
@Size(min = 6, max = 120, message = "password must be between 6 and 120 characters")
|
||||
String password
|
||||
) {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import com.andwati.orders.model.OrderStatus;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record UpdateOrderStatusRequest(
|
||||
@NotNull(message = "status is required")
|
||||
OrderStatus status
|
||||
) {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.andwati.orders.dto.request;
|
||||
|
||||
import com.andwati.orders.model.RideStatus;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record UpdateRideStatusRequest(
|
||||
@NotNull(message = "status is required")
|
||||
RideStatus status
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
import com.andwati.orders.model.Role;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record AuthUserResponse(
|
||||
UUID id,
|
||||
String username,
|
||||
String displayName,
|
||||
Role role
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
public record CsrfResponse(
|
||||
String headerName,
|
||||
String parameterName,
|
||||
String token
|
||||
) {
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import java.util.UUID;
|
||||
|
||||
public record OrderResponse(
|
||||
UUID id,
|
||||
UUID customerId,
|
||||
String customerName,
|
||||
OrderStatus status,
|
||||
List<OrderItemResponse> items,
|
||||
@@ -17,4 +18,4 @@ public record OrderResponse(
|
||||
Instant createdAt,
|
||||
Instant cancelledAt
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -8,6 +8,7 @@ import java.util.UUID;
|
||||
|
||||
public record OrderSummaryResponse(
|
||||
UUID id,
|
||||
UUID customerId,
|
||||
String customerName,
|
||||
OrderStatus status,
|
||||
BigDecimal totalAmount,
|
||||
@@ -16,4 +17,4 @@ public record OrderSummaryResponse(
|
||||
Instant createdAt,
|
||||
Instant cancelledAt
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record ProductResponse(
|
||||
UUID id,
|
||||
String name,
|
||||
String sku,
|
||||
BigDecimal price,
|
||||
String currency,
|
||||
boolean active,
|
||||
int availableQuantity,
|
||||
int reorderLevel,
|
||||
Instant updatedAt
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
import com.andwati.orders.model.RideStatus;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record RideResponse(
|
||||
UUID id,
|
||||
UUID orderId,
|
||||
UUID customerId,
|
||||
String customerName,
|
||||
UUID driverId,
|
||||
String driverName,
|
||||
String pickupLocation,
|
||||
String dropoffLocation,
|
||||
BigDecimal distanceKm,
|
||||
BigDecimal fareAmount,
|
||||
String currency,
|
||||
RideStatus status,
|
||||
Instant requestedAt,
|
||||
Instant acceptedAt,
|
||||
Instant completedAt,
|
||||
Instant cancelledAt
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.andwati.orders.dto.response;
|
||||
|
||||
import com.andwati.orders.model.Role;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public record UserResponse(
|
||||
UUID id,
|
||||
String username,
|
||||
String displayName,
|
||||
Role role,
|
||||
boolean enabled,
|
||||
Instant createdAt
|
||||
) {
|
||||
}
|
||||
+31
-1
@@ -5,6 +5,8 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
@@ -159,6 +161,34 @@ public class GlobalExceptionHandler {
|
||||
);
|
||||
}
|
||||
|
||||
@ExceptionHandler(BadCredentialsException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBadCredentials(
|
||||
BadCredentialsException exception,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
return build(
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
"AUTHENTICATION_FAILED",
|
||||
"Invalid username or password",
|
||||
null,
|
||||
request
|
||||
);
|
||||
}
|
||||
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAccessDenied(
|
||||
AccessDeniedException exception,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
return build(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"ACCESS_DENIED",
|
||||
"You do not have permission to perform this action",
|
||||
null,
|
||||
request
|
||||
);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnexpected(
|
||||
Exception exception,
|
||||
@@ -197,4 +227,4 @@ public class GlobalExceptionHandler {
|
||||
|
||||
return ResponseEntity.status(status).body(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -5,6 +5,6 @@ import java.util.UUID;
|
||||
public class OrderNotCancellableException extends RuntimeException {
|
||||
|
||||
public OrderNotCancellableException(UUID orderId) {
|
||||
super("Order " + orderId + " cannot be cancelled because it is not in PLACED status");
|
||||
super("Order " + orderId + " cannot be cancelled because it is not in PENDING status");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ public class OrderMapper {
|
||||
public OrderResponse toResponse(Order order) {
|
||||
return new OrderResponse(
|
||||
order.getId(),
|
||||
order.getCustomer() == null ? null : order.getCustomer().getId(),
|
||||
order.getCustomerName(),
|
||||
order.getStatus(),
|
||||
order.getItems().stream().map(this::toItemResponse).toList(),
|
||||
@@ -32,6 +33,7 @@ public class OrderMapper {
|
||||
|
||||
return new OrderSummaryResponse(
|
||||
order.getId(),
|
||||
order.getCustomer() == null ? null : order.getCustomer().getId(),
|
||||
order.getCustomerName(),
|
||||
order.getStatus(),
|
||||
order.getTotalAmount(),
|
||||
@@ -60,4 +62,4 @@ public class OrderMapper {
|
||||
item.getLineTotal()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.andwati.orders.mappers;
|
||||
|
||||
import com.andwati.orders.dto.response.ProductResponse;
|
||||
import com.andwati.orders.model.InventoryItem;
|
||||
import com.andwati.orders.model.Product;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ProductMapper {
|
||||
|
||||
public ProductResponse toResponse(Product product, InventoryItem inventoryItem) {
|
||||
return new ProductResponse(
|
||||
product.getId(),
|
||||
product.getName(),
|
||||
product.getSku(),
|
||||
product.getPrice(),
|
||||
product.getCurrency(),
|
||||
product.isActive(),
|
||||
inventoryItem == null ? 0 : inventoryItem.getAvailableQuantity(),
|
||||
inventoryItem == null ? 0 : inventoryItem.getReorderLevel(),
|
||||
inventoryItem == null ? product.getUpdatedAt() : inventoryItem.getUpdatedAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.andwati.orders.mappers;
|
||||
|
||||
import com.andwati.orders.dto.response.RideResponse;
|
||||
import com.andwati.orders.model.Ride;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class RideMapper {
|
||||
|
||||
public RideResponse toResponse(Ride ride) {
|
||||
return new RideResponse(
|
||||
ride.getId(),
|
||||
ride.getOrder() == null ? null : ride.getOrder().getId(),
|
||||
ride.getCustomer().getId(),
|
||||
ride.getCustomer().getDisplayName(),
|
||||
ride.getDriver() == null ? null : ride.getDriver().getId(),
|
||||
ride.getDriver() == null ? null : ride.getDriver().getDisplayName(),
|
||||
ride.getPickupLocation(),
|
||||
ride.getDropoffLocation(),
|
||||
ride.getDistanceKm(),
|
||||
ride.getFareAmount(),
|
||||
ride.getCurrency(),
|
||||
ride.getStatus(),
|
||||
ride.getRequestedAt(),
|
||||
ride.getAcceptedAt(),
|
||||
ride.getCompletedAt(),
|
||||
ride.getCancelledAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.andwati.orders.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(
|
||||
name = "app_users",
|
||||
uniqueConstraints = {
|
||||
@UniqueConstraint(name = "uk_app_users_username", columnNames = "username")
|
||||
}
|
||||
)
|
||||
public class AppUser {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, length = 80)
|
||||
private String username;
|
||||
|
||||
@Column(nullable = false, length = 120)
|
||||
private String displayName;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 30)
|
||||
private Role role;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean enabled = true;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
Instant now = Instant.now();
|
||||
|
||||
if (createdAt == null) {
|
||||
createdAt = now;
|
||||
}
|
||||
|
||||
if (updatedAt == null) {
|
||||
updatedAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
updatedAt = Instant.now();
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public AppUser setId(UUID id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public AppUser setUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public AppUser setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPasswordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public AppUser setPasswordHash(String passwordHash) {
|
||||
this.passwordHash = passwordHash;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Role getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public AppUser setRole(Role role) {
|
||||
this.role = role;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public AppUser setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public AppUser setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public AppUser setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,13 @@ public class Order {
|
||||
@Column(nullable = false, length = 120)
|
||||
private String customerName;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "customer_id")
|
||||
private AppUser customer;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 30)
|
||||
private OrderStatus status = OrderStatus.PLACED;
|
||||
private OrderStatus status = OrderStatus.PENDING;
|
||||
|
||||
@Column(nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal totalAmount = BigDecimal.ZERO;
|
||||
@@ -53,7 +57,7 @@ public class Order {
|
||||
}
|
||||
|
||||
if (status == null) {
|
||||
status = OrderStatus.PLACED;
|
||||
status = OrderStatus.PENDING;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,14 +74,59 @@ public class Order {
|
||||
}
|
||||
|
||||
public boolean isCancellable() {
|
||||
return status == OrderStatus.PLACED;
|
||||
return status == OrderStatus.PENDING;
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
if (!isCancellable()) {
|
||||
throw new IllegalStateException("Only pending orders can be cancelled");
|
||||
}
|
||||
|
||||
this.status = OrderStatus.CANCELLED;
|
||||
this.cancelledAt = Instant.now();
|
||||
}
|
||||
|
||||
public void markDeliveredFromRide() {
|
||||
if (status == OrderStatus.CANCELLED) {
|
||||
throw new IllegalArgumentException("Cancelled orders cannot be delivered");
|
||||
}
|
||||
|
||||
if (status == OrderStatus.DELIVERED) {
|
||||
return;
|
||||
}
|
||||
|
||||
status = OrderStatus.DELIVERED;
|
||||
}
|
||||
|
||||
public void updateStatus(OrderStatus nextStatus) {
|
||||
if (nextStatus == null) {
|
||||
throw new IllegalArgumentException("status is required");
|
||||
}
|
||||
|
||||
if (status == OrderStatus.CANCELLED || status == OrderStatus.DELIVERED) {
|
||||
throw new IllegalArgumentException("Final orders cannot be updated");
|
||||
}
|
||||
|
||||
if (nextStatus == OrderStatus.PENDING) {
|
||||
throw new IllegalArgumentException("Orders cannot be moved back to pending");
|
||||
}
|
||||
|
||||
if (status == OrderStatus.PENDING && (nextStatus == OrderStatus.SHIPPED || nextStatus == OrderStatus.CANCELLED)) {
|
||||
status = nextStatus;
|
||||
if (nextStatus == OrderStatus.CANCELLED) {
|
||||
cancelledAt = Instant.now();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (status == OrderStatus.SHIPPED && nextStatus == OrderStatus.DELIVERED) {
|
||||
status = nextStatus;
|
||||
return;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Invalid order status transition");
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
@@ -96,6 +145,15 @@ public class Order {
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppUser getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public Order setCustomer(AppUser customer) {
|
||||
this.customer = customer;
|
||||
return this;
|
||||
}
|
||||
|
||||
public OrderStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.andwati.orders.model;
|
||||
|
||||
|
||||
public enum OrderStatus {
|
||||
PLACED,
|
||||
PENDING,
|
||||
SHIPPED,
|
||||
DELIVERED,
|
||||
CANCELLED
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.andwati.orders.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "rides")
|
||||
public class Ride {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "customer_id", nullable = false)
|
||||
private AppUser customer;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "driver_id")
|
||||
private AppUser driver;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "order_id")
|
||||
private Order order;
|
||||
|
||||
@Column(nullable = false, length = 160)
|
||||
private String pickupLocation;
|
||||
|
||||
@Column(nullable = false, length = 160)
|
||||
private String dropoffLocation;
|
||||
|
||||
@Column(nullable = false, precision = 8, scale = 2)
|
||||
private BigDecimal distanceKm;
|
||||
|
||||
@Column(precision = 12, scale = 2)
|
||||
private BigDecimal fareAmount;
|
||||
|
||||
@Column(nullable = false, length = 3)
|
||||
private String currency = "KES";
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 30)
|
||||
private RideStatus status = RideStatus.REQUESTED;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Instant requestedAt;
|
||||
|
||||
private Instant acceptedAt;
|
||||
|
||||
private Instant completedAt;
|
||||
|
||||
private Instant cancelledAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
if (requestedAt == null) {
|
||||
requestedAt = Instant.now();
|
||||
}
|
||||
|
||||
if (status == null) {
|
||||
status = RideStatus.REQUESTED;
|
||||
}
|
||||
}
|
||||
|
||||
public void accept(AppUser driver, BigDecimal fareAmount, String currency) {
|
||||
if (status != RideStatus.REQUESTED) {
|
||||
throw new IllegalArgumentException("Only requested rides can be accepted");
|
||||
}
|
||||
|
||||
this.driver = driver;
|
||||
this.fareAmount = fareAmount;
|
||||
this.currency = currency;
|
||||
this.status = RideStatus.ACCEPTED;
|
||||
this.acceptedAt = Instant.now();
|
||||
}
|
||||
|
||||
public void complete(AppUser driver) {
|
||||
if (status != RideStatus.ACCEPTED) {
|
||||
throw new IllegalArgumentException("Only accepted rides can be completed");
|
||||
}
|
||||
|
||||
if (this.driver == null || !this.driver.getId().equals(driver.getId())) {
|
||||
throw new IllegalArgumentException("Only the assigned driver can complete this ride");
|
||||
}
|
||||
|
||||
this.status = RideStatus.COMPLETED;
|
||||
this.completedAt = Instant.now();
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
if (status == RideStatus.COMPLETED) {
|
||||
throw new IllegalArgumentException("Completed rides cannot be cancelled");
|
||||
}
|
||||
|
||||
this.status = RideStatus.CANCELLED;
|
||||
this.cancelledAt = Instant.now();
|
||||
}
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Ride setId(UUID id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppUser getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public Ride setCustomer(AppUser customer) {
|
||||
this.customer = customer;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppUser getDriver() {
|
||||
return driver;
|
||||
}
|
||||
|
||||
public Ride setDriver(AppUser driver) {
|
||||
this.driver = driver;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public Ride setOrder(Order order) {
|
||||
this.order = order;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPickupLocation() {
|
||||
return pickupLocation;
|
||||
}
|
||||
|
||||
public Ride setPickupLocation(String pickupLocation) {
|
||||
this.pickupLocation = pickupLocation;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDropoffLocation() {
|
||||
return dropoffLocation;
|
||||
}
|
||||
|
||||
public Ride setDropoffLocation(String dropoffLocation) {
|
||||
this.dropoffLocation = dropoffLocation;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getDistanceKm() {
|
||||
return distanceKm;
|
||||
}
|
||||
|
||||
public Ride setDistanceKm(BigDecimal distanceKm) {
|
||||
this.distanceKm = distanceKm;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getFareAmount() {
|
||||
return fareAmount;
|
||||
}
|
||||
|
||||
public Ride setFareAmount(BigDecimal fareAmount) {
|
||||
this.fareAmount = fareAmount;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public Ride setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
return this;
|
||||
}
|
||||
|
||||
public RideStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public Ride setStatus(RideStatus status) {
|
||||
this.status = status;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getRequestedAt() {
|
||||
return requestedAt;
|
||||
}
|
||||
|
||||
public Ride setRequestedAt(Instant requestedAt) {
|
||||
this.requestedAt = requestedAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getAcceptedAt() {
|
||||
return acceptedAt;
|
||||
}
|
||||
|
||||
public Ride setAcceptedAt(Instant acceptedAt) {
|
||||
this.acceptedAt = acceptedAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getCompletedAt() {
|
||||
return completedAt;
|
||||
}
|
||||
|
||||
public Ride setCompletedAt(Instant completedAt) {
|
||||
this.completedAt = completedAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Instant getCancelledAt() {
|
||||
return cancelledAt;
|
||||
}
|
||||
|
||||
public Ride setCancelledAt(Instant cancelledAt) {
|
||||
this.cancelledAt = cancelledAt;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.andwati.orders.model;
|
||||
|
||||
public enum RideStatus {
|
||||
REQUESTED,
|
||||
ACCEPTED,
|
||||
COMPLETED,
|
||||
CANCELLED
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.andwati.orders.model;
|
||||
|
||||
public enum Role {
|
||||
ADMIN,
|
||||
CUSTOMER,
|
||||
DRIVER
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.andwati.orders.repository;
|
||||
|
||||
import com.andwati.orders.model.AppUser;
|
||||
import com.andwati.orders.model.Role;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AppUserRepository extends JpaRepository<AppUser, UUID> {
|
||||
|
||||
Optional<AppUser> findByUsernameIgnoreCase(String username);
|
||||
|
||||
boolean existsByUsernameIgnoreCase(String username);
|
||||
|
||||
boolean existsByRole(Role role);
|
||||
|
||||
List<AppUser> findByRoleOrderByCreatedAtDesc(Role role);
|
||||
|
||||
List<AppUser> findAllByOrderByCreatedAtDesc();
|
||||
}
|
||||
@@ -10,6 +10,6 @@ import java.util.UUID;
|
||||
|
||||
public interface OrderRepository extends JpaRepository<Order, UUID>, JpaSpecificationExecutor<Order> {
|
||||
|
||||
@EntityGraph(attributePaths = {"items", "items.product"})
|
||||
@EntityGraph(attributePaths = {"items", "items.product", "customer"})
|
||||
Optional<Order> findWithItemsById(UUID id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,12 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ProductRepository extends JpaRepository<Product, UUID> {
|
||||
|
||||
List<Product> findByIdIn(Collection<UUID> ids);
|
||||
}
|
||||
|
||||
Optional<Product> findBySkuIgnoreCase(String sku);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.andwati.orders.repository;
|
||||
|
||||
import com.andwati.orders.model.Ride;
|
||||
import com.andwati.orders.model.RideStatus;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface RideRepository extends JpaRepository<Ride, UUID> {
|
||||
|
||||
@EntityGraph(attributePaths = {"customer", "driver", "order"})
|
||||
List<Ride> findByCustomer_IdOrderByRequestedAtDesc(UUID customerId);
|
||||
|
||||
@EntityGraph(attributePaths = {"customer", "driver", "order"})
|
||||
List<Ride> findByDriver_IdOrderByRequestedAtDesc(UUID driverId);
|
||||
|
||||
@EntityGraph(attributePaths = {"customer", "driver", "order"})
|
||||
List<Ride> findByStatusOrderByRequestedAtAsc(RideStatus status);
|
||||
|
||||
@EntityGraph(attributePaths = {"customer", "driver", "order"})
|
||||
List<Ride> findAllByOrderByRequestedAtDesc();
|
||||
|
||||
@EntityGraph(attributePaths = {"customer", "driver", "order"})
|
||||
Optional<Ride> findWithUsersById(UUID id);
|
||||
|
||||
boolean existsByOrder_Id(UUID orderId);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.andwati.orders.services;
|
||||
|
||||
import com.andwati.orders.repository.AppUserRepository;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class AppUserDetailsService implements UserDetailsService {
|
||||
|
||||
private final AppUserRepository appUserRepository;
|
||||
|
||||
public AppUserDetailsService(AppUserRepository appUserRepository) {
|
||||
this.appUserRepository = appUserRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
var user = appUserRepository.findByUsernameIgnoreCase(username.trim().toLowerCase())
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
|
||||
return new User(
|
||||
user.getUsername(),
|
||||
user.getPasswordHash(),
|
||||
user.isEnabled(),
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_" + user.getRole().name()))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.andwati.orders.services;
|
||||
|
||||
import com.andwati.orders.dto.request.AdminUserRequest;
|
||||
import com.andwati.orders.dto.request.RegisterRequest;
|
||||
import com.andwati.orders.dto.response.AuthUserResponse;
|
||||
import com.andwati.orders.dto.response.UserResponse;
|
||||
import com.andwati.orders.model.AppUser;
|
||||
import com.andwati.orders.model.Role;
|
||||
import com.andwati.orders.repository.AppUserRepository;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class AppUserService {
|
||||
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public AppUserService(AppUserRepository appUserRepository, PasswordEncoder passwordEncoder) {
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthUserResponse registerCustomer(RegisterRequest request) {
|
||||
String username = normalizeUsername(request.username());
|
||||
|
||||
if (appUserRepository.existsByUsernameIgnoreCase(username)) {
|
||||
throw new IllegalArgumentException("Username is already taken");
|
||||
}
|
||||
|
||||
AppUser user = new AppUser()
|
||||
.setUsername(username)
|
||||
.setDisplayName(request.displayName().trim())
|
||||
.setPasswordHash(passwordEncoder.encode(request.password()))
|
||||
.setRole(Role.CUSTOMER)
|
||||
.setEnabled(true);
|
||||
|
||||
return toResponse(appUserRepository.save(user));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AppUser getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication == null || !authentication.isAuthenticated()) {
|
||||
throw new IllegalArgumentException("Authentication is required");
|
||||
}
|
||||
|
||||
return appUserRepository.findByUsernameIgnoreCase(authentication.getName())
|
||||
.orElseThrow(() -> new IllegalArgumentException("Authenticated user was not found"));
|
||||
}
|
||||
|
||||
public AuthUserResponse toResponse(AppUser user) {
|
||||
return new AuthUserResponse(
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
user.getDisplayName(),
|
||||
user.getRole()
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserResponse> listUsers() {
|
||||
return appUserRepository.findAllByOrderByCreatedAtDesc()
|
||||
.stream()
|
||||
.map(this::toUserResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserResponse> listCustomers() {
|
||||
return appUserRepository.findByRoleOrderByCreatedAtDesc(Role.CUSTOMER)
|
||||
.stream()
|
||||
.map(this::toUserResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserResponse> listDrivers() {
|
||||
return appUserRepository.findByRoleOrderByCreatedAtDesc(Role.DRIVER)
|
||||
.stream()
|
||||
.map(this::toUserResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserResponse createUser(AdminUserRequest request) {
|
||||
String username = normalizeUsername(request.username());
|
||||
|
||||
if (appUserRepository.existsByUsernameIgnoreCase(username)) {
|
||||
throw new IllegalArgumentException("Username is already taken");
|
||||
}
|
||||
|
||||
if (request.password() == null || request.password().isBlank()) {
|
||||
throw new IllegalArgumentException("password is required");
|
||||
}
|
||||
|
||||
AppUser user = new AppUser()
|
||||
.setUsername(username)
|
||||
.setDisplayName(request.displayName().trim())
|
||||
.setPasswordHash(passwordEncoder.encode(request.password()))
|
||||
.setRole(request.role())
|
||||
.setEnabled(request.enabled());
|
||||
|
||||
return toUserResponse(appUserRepository.save(user));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserResponse updateUser(UUID id, AdminUserRequest request) {
|
||||
AppUser user = appUserRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("User was not found"));
|
||||
String username = normalizeUsername(request.username());
|
||||
|
||||
appUserRepository.findByUsernameIgnoreCase(username)
|
||||
.filter(existing -> !existing.getId().equals(id))
|
||||
.ifPresent(existing -> {
|
||||
throw new IllegalArgumentException("Username is already taken");
|
||||
});
|
||||
|
||||
user.setUsername(username)
|
||||
.setDisplayName(request.displayName().trim())
|
||||
.setRole(request.role())
|
||||
.setEnabled(request.enabled());
|
||||
|
||||
if (request.password() != null && !request.password().isBlank()) {
|
||||
user.setPasswordHash(passwordEncoder.encode(request.password()));
|
||||
}
|
||||
|
||||
return toUserResponse(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserResponse disableUser(UUID id) {
|
||||
AppUser user = appUserRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("User was not found"));
|
||||
user.setEnabled(false);
|
||||
return toUserResponse(user);
|
||||
}
|
||||
|
||||
private UserResponse toUserResponse(AppUser user) {
|
||||
return new UserResponse(
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
user.getDisplayName(),
|
||||
user.getRole(),
|
||||
user.isEnabled(),
|
||||
user.getCreatedAt()
|
||||
);
|
||||
}
|
||||
|
||||
public String normalizeUsername(String username) {
|
||||
return username.trim().toLowerCase();
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import com.andwati.orders.model.*;
|
||||
import com.andwati.orders.repository.InventoryItemRepository;
|
||||
import com.andwati.orders.repository.OrderRepository;
|
||||
import com.andwati.orders.repository.ProductRepository;
|
||||
import com.andwati.orders.repository.RideRepository;
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
@@ -33,22 +34,33 @@ public class OrderService {
|
||||
private final OrderRepository orderRepository;
|
||||
private final ProductRepository productRepository;
|
||||
private final InventoryItemRepository inventoryItemRepository;
|
||||
private final RideRepository rideRepository;
|
||||
private final OrderMapper orderMapper;
|
||||
private final AppUserService appUserService;
|
||||
|
||||
public OrderService(
|
||||
OrderRepository orderRepository,
|
||||
ProductRepository productRepository,
|
||||
InventoryItemRepository inventoryItemRepository,
|
||||
OrderMapper orderMapper
|
||||
RideRepository rideRepository,
|
||||
OrderMapper orderMapper,
|
||||
AppUserService appUserService
|
||||
) {
|
||||
this.orderRepository = orderRepository;
|
||||
this.productRepository = productRepository;
|
||||
this.inventoryItemRepository = inventoryItemRepository;
|
||||
this.rideRepository = rideRepository;
|
||||
this.orderMapper = orderMapper;
|
||||
this.appUserService = appUserService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrderResponse placeOrder(CreateOrderRequest request) {
|
||||
AppUser customer = appUserService.getCurrentUser();
|
||||
if (customer.getRole() != Role.CUSTOMER) {
|
||||
throw new IllegalArgumentException("Only customers can place orders");
|
||||
}
|
||||
|
||||
Map<UUID, Integer> requestedQuantities = normalizeItems(request);
|
||||
|
||||
Map<UUID, Product> productsById = productRepository.findByIdIn(requestedQuantities.keySet())
|
||||
@@ -69,8 +81,9 @@ public class OrderService {
|
||||
validateStockAvailability(requestedQuantities, inventoryByProductId);
|
||||
|
||||
Order order = new Order();
|
||||
order.setCustomerName(request.customerName());
|
||||
order.setStatus(OrderStatus.PLACED);
|
||||
order.setCustomer(customer);
|
||||
order.setCustomerName(customer.getDisplayName());
|
||||
order.setStatus(OrderStatus.PENDING);
|
||||
order.setCurrency("KES");
|
||||
order.setCreatedAt(Instant.now());
|
||||
|
||||
@@ -91,6 +104,18 @@ public class OrderService {
|
||||
|
||||
Order savedOrder = orderRepository.save(order);
|
||||
|
||||
if (request.deliveryRide() != null) {
|
||||
Ride ride = new Ride()
|
||||
.setOrder(savedOrder)
|
||||
.setCustomer(customer)
|
||||
.setPickupLocation(request.deliveryRide().pickupLocation().trim())
|
||||
.setDropoffLocation(request.deliveryRide().dropoffLocation().trim())
|
||||
.setDistanceKm(request.deliveryRide().distanceKm())
|
||||
.setStatus(RideStatus.REQUESTED);
|
||||
|
||||
rideRepository.save(ride);
|
||||
}
|
||||
|
||||
return orderMapper.toResponse(savedOrder);
|
||||
}
|
||||
|
||||
@@ -99,6 +124,8 @@ public class OrderService {
|
||||
Order order = orderRepository.findWithItemsById(orderId)
|
||||
.orElseThrow(() -> new OrderNotFoundException(orderId));
|
||||
|
||||
assertCanAccessOrder(order);
|
||||
|
||||
if (!order.isCancellable()) {
|
||||
throw new OrderNotCancellableException(orderId);
|
||||
}
|
||||
@@ -137,6 +164,8 @@ public class OrderService {
|
||||
Order order = orderRepository.findWithItemsById(orderId)
|
||||
.orElseThrow(() -> new OrderNotFoundException(orderId));
|
||||
|
||||
assertCanAccessOrder(order);
|
||||
|
||||
return orderMapper.toResponse(order);
|
||||
}
|
||||
|
||||
@@ -157,7 +186,9 @@ public class OrderService {
|
||||
Sort.by(Sort.Direction.DESC, "createdAt")
|
||||
);
|
||||
|
||||
var result = orderRepository.findAll(buildOrderSpecification(status, from, to), pageable);
|
||||
AppUser currentUser = appUserService.getCurrentUser();
|
||||
|
||||
var result = orderRepository.findAll(buildOrderSpecification(status, from, to, currentUser), pageable);
|
||||
|
||||
var items = result.getContent()
|
||||
.stream()
|
||||
@@ -173,6 +204,25 @@ public class OrderService {
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrderResponse updateStatus(UUID orderId, OrderStatus status) {
|
||||
AppUser currentUser = appUserService.getCurrentUser();
|
||||
if (currentUser.getRole() != Role.ADMIN) {
|
||||
throw new IllegalArgumentException("Only admins can update order status");
|
||||
}
|
||||
|
||||
Order order = orderRepository.findWithItemsById(orderId)
|
||||
.orElseThrow(() -> new OrderNotFoundException(orderId));
|
||||
|
||||
if (status == OrderStatus.CANCELLED && order.isCancellable()) {
|
||||
cancelOrder(orderId);
|
||||
return orderMapper.toResponse(order);
|
||||
}
|
||||
|
||||
order.updateStatus(status);
|
||||
return orderMapper.toResponse(order);
|
||||
}
|
||||
|
||||
private Map<UUID, Integer> normalizeItems(CreateOrderRequest request) {
|
||||
Map<UUID, Integer> quantities = new HashMap<>();
|
||||
|
||||
@@ -236,7 +286,8 @@ public class OrderService {
|
||||
private Specification<Order> buildOrderSpecification(
|
||||
OrderStatus status,
|
||||
LocalDate from,
|
||||
LocalDate to
|
||||
LocalDate to,
|
||||
AppUser currentUser
|
||||
) {
|
||||
return (root, query, criteriaBuilder) -> {
|
||||
var predicates = new java.util.ArrayList<Predicate>();
|
||||
@@ -255,7 +306,29 @@ public class OrderService {
|
||||
predicates.add(criteriaBuilder.lessThan(root.get("createdAt"), toExclusive));
|
||||
}
|
||||
|
||||
if (currentUser.getRole() == Role.CUSTOMER) {
|
||||
predicates.add(criteriaBuilder.equal(root.get("customer").get("id"), currentUser.getId()));
|
||||
} else if (currentUser.getRole() != Role.ADMIN) {
|
||||
predicates.add(criteriaBuilder.disjunction());
|
||||
}
|
||||
|
||||
return criteriaBuilder.and(predicates.toArray(Predicate[]::new));
|
||||
};
|
||||
}
|
||||
|
||||
private void assertCanAccessOrder(Order order) {
|
||||
AppUser currentUser = appUserService.getCurrentUser();
|
||||
|
||||
if (currentUser.getRole() == Role.ADMIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentUser.getRole() == Role.CUSTOMER
|
||||
&& order.getCustomer() != null
|
||||
&& currentUser.getId().equals(order.getCustomer().getId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("You cannot access this order");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,143 @@
|
||||
package com.andwati.orders.services;
|
||||
|
||||
import com.andwati.orders.dto.request.ProductRequest;
|
||||
import com.andwati.orders.dto.response.ProductResponse;
|
||||
import com.andwati.orders.exception.ProductNotFoundException;
|
||||
import com.andwati.orders.mappers.ProductMapper;
|
||||
import com.andwati.orders.model.InventoryItem;
|
||||
import com.andwati.orders.model.Product;
|
||||
import com.andwati.orders.model.Role;
|
||||
import com.andwati.orders.repository.InventoryItemRepository;
|
||||
import com.andwati.orders.repository.ProductRepository;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class ProductService {
|
||||
|
||||
private final ProductRepository productRepository;
|
||||
private final InventoryItemRepository inventoryItemRepository;
|
||||
private final ProductMapper productMapper;
|
||||
private final AppUserService appUserService;
|
||||
|
||||
public ProductService(ProductRepository productRepository) {
|
||||
public ProductService(
|
||||
ProductRepository productRepository,
|
||||
InventoryItemRepository inventoryItemRepository,
|
||||
ProductMapper productMapper,
|
||||
AppUserService appUserService
|
||||
) {
|
||||
this.productRepository = productRepository;
|
||||
this.inventoryItemRepository = inventoryItemRepository;
|
||||
this.productMapper = productMapper;
|
||||
this.appUserService = appUserService;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public java.util.List<ProductResponse> listProducts() {
|
||||
Role role = currentRoleOrCustomer();
|
||||
var products = productRepository.findAll(Sort.by("name"));
|
||||
var inventoriesByProductId = inventoryItemRepository.findByProduct_IdIn(
|
||||
products.stream().map(Product::getId).toList()
|
||||
)
|
||||
.stream()
|
||||
.collect(Collectors.toMap(item -> item.getProduct().getId(), Function.identity()));
|
||||
|
||||
return products.stream()
|
||||
.filter(product -> role == Role.ADMIN || product.isActive())
|
||||
.map(product -> productMapper.toResponse(product, inventoriesByProductId.get(product.getId())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ProductResponse getProduct(UUID id) {
|
||||
Product product = getProductOrThrow(id);
|
||||
|
||||
if (!product.isActive() && currentRoleOrCustomer() != Role.ADMIN) {
|
||||
throw new ProductNotFoundException(id);
|
||||
}
|
||||
|
||||
InventoryItem inventoryItem = inventoryItemRepository.findByProduct_Id(id).orElse(null);
|
||||
return productMapper.toResponse(product, inventoryItem);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductResponse createProduct(ProductRequest request) {
|
||||
Product product = new Product()
|
||||
.setName(request.name().trim())
|
||||
.setSku(request.sku().trim())
|
||||
.setPrice(request.price())
|
||||
.setCurrency(request.currency().trim().toUpperCase())
|
||||
.setActive(request.active())
|
||||
.setCreatedAt(Instant.now())
|
||||
.setUpdatedAt(Instant.now());
|
||||
|
||||
Product savedProduct = productRepository.save(product);
|
||||
|
||||
InventoryItem inventoryItem = new InventoryItem()
|
||||
.setProduct(savedProduct)
|
||||
.setAvailableQuantity(request.availableQuantity())
|
||||
.setReservedQuantity(0)
|
||||
.setReorderLevel(request.reorderLevel())
|
||||
.setUpdatedAt(Instant.now());
|
||||
|
||||
inventoryItemRepository.save(inventoryItem);
|
||||
|
||||
return productMapper.toResponse(savedProduct, inventoryItem);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductResponse updateProduct(UUID id, ProductRequest request) {
|
||||
Product product = getProductOrThrow(id)
|
||||
.setName(request.name().trim())
|
||||
.setSku(request.sku().trim())
|
||||
.setPrice(request.price())
|
||||
.setCurrency(request.currency().trim().toUpperCase())
|
||||
.setActive(request.active());
|
||||
|
||||
InventoryItem inventoryItem = inventoryItemRepository.findByProduct_Id(id)
|
||||
.orElseGet(() -> new InventoryItem()
|
||||
.setProduct(product)
|
||||
.setReservedQuantity(0)
|
||||
);
|
||||
|
||||
inventoryItem
|
||||
.setAvailableQuantity(request.availableQuantity())
|
||||
.setReorderLevel(request.reorderLevel())
|
||||
.setUpdatedAt(Instant.now());
|
||||
|
||||
inventoryItemRepository.save(inventoryItem);
|
||||
|
||||
return productMapper.toResponse(product, inventoryItem);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductResponse deactivateProduct(UUID id) {
|
||||
Product product = getProductOrThrow(id).setActive(false);
|
||||
InventoryItem inventoryItem = inventoryItemRepository.findByProduct_Id(id).orElse(null);
|
||||
return productMapper.toResponse(product, inventoryItem);
|
||||
}
|
||||
|
||||
public Product getProductOrThrow(UUID id) {
|
||||
return productRepository.findById(id)
|
||||
.orElseThrow(() -> new ProductNotFoundException(id));
|
||||
}
|
||||
}
|
||||
|
||||
private Role currentRoleOrCustomer() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getName())) {
|
||||
return Role.CUSTOMER;
|
||||
}
|
||||
|
||||
return appUserService.getCurrentUser().getRole();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package com.andwati.orders.services;
|
||||
|
||||
import com.andwati.orders.dto.request.CreateRideRequest;
|
||||
import com.andwati.orders.dto.response.RideResponse;
|
||||
import com.andwati.orders.mappers.RideMapper;
|
||||
import com.andwati.orders.model.AppUser;
|
||||
import com.andwati.orders.model.Order;
|
||||
import com.andwati.orders.model.Ride;
|
||||
import com.andwati.orders.model.RideStatus;
|
||||
import com.andwati.orders.model.Role;
|
||||
import com.andwati.orders.repository.OrderRepository;
|
||||
import com.andwati.orders.repository.RideRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class RideService {
|
||||
|
||||
private final RideRepository rideRepository;
|
||||
private final OrderRepository orderRepository;
|
||||
private final AppUserService appUserService;
|
||||
private final FareCalculationService fareCalculationService;
|
||||
private final RideMapper rideMapper;
|
||||
|
||||
public RideService(
|
||||
RideRepository rideRepository,
|
||||
OrderRepository orderRepository,
|
||||
AppUserService appUserService,
|
||||
FareCalculationService fareCalculationService,
|
||||
RideMapper rideMapper
|
||||
) {
|
||||
this.rideRepository = rideRepository;
|
||||
this.orderRepository = orderRepository;
|
||||
this.appUserService = appUserService;
|
||||
this.fareCalculationService = fareCalculationService;
|
||||
this.rideMapper = rideMapper;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RideResponse requestRide(CreateRideRequest request) {
|
||||
AppUser customer = appUserService.getCurrentUser();
|
||||
if (customer.getRole() != Role.CUSTOMER) {
|
||||
throw new IllegalArgumentException("Only customers can request rides");
|
||||
}
|
||||
|
||||
Order order = orderRepository.findWithItemsById(request.orderId())
|
||||
.orElseThrow(() -> new IllegalArgumentException("Order was not found"));
|
||||
|
||||
if (order.getCustomer() == null || !customer.getId().equals(order.getCustomer().getId())) {
|
||||
throw new IllegalArgumentException("You can only request rides for your own orders");
|
||||
}
|
||||
|
||||
if (rideRepository.existsByOrder_Id(order.getId())) {
|
||||
throw new IllegalArgumentException("This order already has a ride request");
|
||||
}
|
||||
|
||||
Ride ride = new Ride()
|
||||
.setOrder(order)
|
||||
.setCustomer(customer)
|
||||
.setPickupLocation(request.pickupLocation().trim())
|
||||
.setDropoffLocation(request.dropoffLocation().trim())
|
||||
.setDistanceKm(request.distanceKm())
|
||||
.setStatus(RideStatus.REQUESTED);
|
||||
|
||||
return rideMapper.toResponse(rideRepository.save(ride));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<RideResponse> listRides() {
|
||||
AppUser currentUser = appUserService.getCurrentUser();
|
||||
|
||||
List<Ride> rides = switch (currentUser.getRole()) {
|
||||
case ADMIN -> rideRepository.findAllByOrderByRequestedAtDesc();
|
||||
case CUSTOMER -> rideRepository.findByCustomer_IdOrderByRequestedAtDesc(currentUser.getId());
|
||||
case DRIVER -> {
|
||||
var requested = rideRepository.findByStatusOrderByRequestedAtAsc(RideStatus.REQUESTED);
|
||||
var assigned = rideRepository.findByDriver_IdOrderByRequestedAtDesc(currentUser.getId());
|
||||
yield java.util.stream.Stream.concat(requested.stream(), assigned.stream())
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
};
|
||||
|
||||
return rides.stream().map(rideMapper::toResponse).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RideResponse acceptRide(UUID id) {
|
||||
AppUser driver = appUserService.getCurrentUser();
|
||||
if (driver.getRole() != Role.DRIVER) {
|
||||
throw new IllegalArgumentException("Only drivers can accept rides");
|
||||
}
|
||||
|
||||
Ride ride = getRideOrThrow(id);
|
||||
var fare = fareCalculationService.calculateFare(ride.getDistanceKm(), null);
|
||||
ride.accept(driver, fare.calculatedFare(), fare.currency());
|
||||
|
||||
return rideMapper.toResponse(ride);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RideResponse completeRide(UUID id) {
|
||||
AppUser driver = appUserService.getCurrentUser();
|
||||
if (driver.getRole() != Role.DRIVER) {
|
||||
throw new IllegalArgumentException("Only drivers can complete rides");
|
||||
}
|
||||
|
||||
Ride ride = getRideOrThrow(id);
|
||||
ride.complete(driver);
|
||||
completeAttachedOrder(ride);
|
||||
|
||||
return rideMapper.toResponse(ride);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RideResponse cancelRide(UUID id) {
|
||||
AppUser currentUser = appUserService.getCurrentUser();
|
||||
Ride ride = getRideOrThrow(id);
|
||||
|
||||
if (currentUser.getRole() == Role.CUSTOMER
|
||||
&& !currentUser.getId().equals(ride.getCustomer().getId())) {
|
||||
throw new IllegalArgumentException("You cannot cancel this ride");
|
||||
}
|
||||
|
||||
if (currentUser.getRole() == Role.DRIVER) {
|
||||
throw new IllegalArgumentException("Drivers cannot cancel rides");
|
||||
}
|
||||
|
||||
ride.cancel();
|
||||
return rideMapper.toResponse(ride);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RideResponse updateStatus(UUID id, RideStatus status) {
|
||||
AppUser currentUser = appUserService.getCurrentUser();
|
||||
if (currentUser.getRole() != Role.ADMIN) {
|
||||
throw new IllegalArgumentException("Only admins can update ride status");
|
||||
}
|
||||
|
||||
Ride ride = getRideOrThrow(id);
|
||||
|
||||
if (status == RideStatus.CANCELLED) {
|
||||
ride.cancel();
|
||||
} else if (status == RideStatus.COMPLETED) {
|
||||
if (ride.getDriver() == null) {
|
||||
throw new IllegalArgumentException("A ride must have a driver before completion");
|
||||
}
|
||||
ride.setStatus(RideStatus.COMPLETED).setCompletedAt(java.time.Instant.now());
|
||||
completeAttachedOrder(ride);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Admins can only cancel or complete rides");
|
||||
}
|
||||
|
||||
return rideMapper.toResponse(ride);
|
||||
}
|
||||
|
||||
private Ride getRideOrThrow(UUID id) {
|
||||
return rideRepository.findWithUsersById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Ride was not found"));
|
||||
}
|
||||
|
||||
private void completeAttachedOrder(Ride ride) {
|
||||
if (ride.getOrder() != null) {
|
||||
ride.getOrder().markDeliveredFromRide();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
server.port=8080
|
||||
server.port=${PORT:8080}
|
||||
|
||||
spring.application.name=orders
|
||||
|
||||
spring.datasource.url=${DATABASE_URL}
|
||||
spring.datasource.username=${DATABASE_USERNAME}
|
||||
spring.datasource.password=${DATABASE_PASSWORD}
|
||||
spring.datasource.url=${SPRING_DATASOURCE_URL:${DATABASE_URL:}}
|
||||
spring.datasource.username=${SPRING_DATASOURCE_USERNAME:${DATABASE_USERNAME:}}
|
||||
spring.datasource.password=${SPRING_DATASOURCE_PASSWORD:${DATABASE_PASSWORD:}}
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
@@ -21,8 +21,9 @@ fare.default-surge-multiplier=${FARE_DEFAULT_SURGE_MULTIPLIER:1.0}
|
||||
fare.currency=${FARE_CURRENCY:KES}
|
||||
|
||||
app.seed-data=${SEED_DATA:true}
|
||||
app.cors.allowed-origins=${APP_CORS_ALLOWED_ORIGINS:http://localhost:3000}
|
||||
springdoc.api-docs.path=/api-docs
|
||||
springdoc.swagger-ui.path=/swagger-ui.html
|
||||
springdoc.swagger-ui.operations-sorter=method
|
||||
springdoc.swagger-ui.tags-sorter=alpha
|
||||
springdoc.swagger-ui.try-it-out-enabled=true
|
||||
springdoc.swagger-ui.try-it-out-enabled=true
|
||||
|
||||
@@ -2,8 +2,10 @@ package com.andwati.orders;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
class OrdersBackendApplicationTests {
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user