Untitled
unknown
plain_text
2 years ago
17 kB
8
Indexable
Java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;
@Entity
public class Deal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private double price;
private int quantity;
private LocalDateTime startTime;
private LocalDateTime endTime;
private int maxClaimQuantity;
// Getters and setters
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDateTime;
import java.util.List;
public interface DealRepository extends JpaRepository<Deal, Integer> {
List<Deal> findByStartTimeBeforeAndEndTimeAfter(LocalDateTime startTime, LocalDateTime endTime);
List<Deal> findByMaxClaimQuantityGreaterThan(int claimedQuantity);
}
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class DealService {
private final DealRepository dealRepository;
@Autowired
public DealService(DealRepository dealRepository) {
this.dealRepository = dealRepository;
}
@Transactional
public Deal saveDeal(Deal deal) {
// Validate input deal
if (deal.getName() == null || deal.getName().isEmpty() || deal.getPrice() <= 0 || deal.getQuantity() <= 0) {
throw new RuntimeException("Invalid deal input");
}
// Save the deal to the database and return the created deal
return dealRepository.save(deal);
}
public List<Deal> findDealsByStartTimeBeforeAndEndTimeAfter(LocalDateTime startTime, LocalDateTime endTime) {
return dealRepository.findByStartTimeBeforeAndEndTimeAfter(startTime, endTime);
}
public List<Deal> findDealsByMaxClaimQuantityGreaterThan(int claimedQuantity) {
return dealRepository.findByMaxClaimQuantityGreaterThan(claimedQuantity);
}
public void updateDealClaimQuantity(int dealId, int claimedQuantity) {
Deal deal = dealRepository.findById(dealId).orElse(null);
if (deal != null && deal.getClaimQuantity() < deal.getMaxClaimQuantity()) {
deal.setClaimQuantity(deal.getClaimQuantity() + claimedQuantity);
dealRepository.save(deal);
}
}
}
@Service
public class DealService {
@Autowired
private DealRepository dealRepository;
public Deal createDeal(Deal deal) {
if (deal.getPrice() <= 0 || deal.getQuantity() <= 0 || deal.getStartTime().isAfter(deal.getEndTime())) {
throw new IllegalArgumentException("Invalid deal data");
}
return dealRepository.save(deal);
}
public void endDeal(int dealId) {
Deal deal = dealRepository.findById(dealId).orElseThrow(() -> new ResourceNotFoundException("Deal not found"));
deal.setEndTime(LocalDateTime.now());
dealRepository.save(deal);
}
public Deal updateDeal(int dealId, Deal updatedDeal) {
Deal deal = dealRepository.findById(dealId).orElseThrow(() -> new ResourceNotFoundException("Deal not found"));
if (updatedDeal.getPrice() <= 0 || updatedDeal.getQuantity() <= 0 || updatedDeal.getStartTime().isAfter(updatedDeal.getEndTime())) {
throw new IllegalArgumentException("Invalid updated deal data");
}
deal.setPrice(updatedDeal.getPrice());
deal.setQuantity(updatedDeal.getQuantity());
deal.setStartTime(updatedDeal.getStartTime());
deal.setEndTime(updatedDeal.getEndTime());
return dealRepository.save(deal);
}
@Transactional
public boolean claimDeal(int dealId, int quantity) {
Deal deal = dealRepository.findById(dealId).orElseThrow(() -> new ResourceNotFoundException("Deal not found"));
if (!deal.isActive() || quantity <= 0 || quantity > deal.getRemainingQuantity()) {
return false;
}
deal.setClaimedQuantity(deal.getClaimedQuantity() + quantity);
if (deal.getClaimedQuantity() == deal.getQuantity()) {
endDeal(dealId);
}
dealRepository.save(deal);
return true;
}
// Getter methods for existing deal attributes
}
@Service
public class DealServiceImpl implements DealService {
@Autowired
private DealRepository dealRepository;
@Autowired
private PurchaseHistoryRepository purchaseHistoryRepository;
@Autowired
private InventoryService inventoryService;
@Override
@Transactional
public Deal createDeal(Deal deal) {
validateDealInput(deal);
try {
Deal createdDeal = dealRepository.save(deal);
inventoryService.decreaseItemStock(createdDeal.getItemId(), createdDeal.getItemsAvailable());
return createdDeal;
} catch (Exception e) {
// Handle exceptions appropriately
}
}
private void validateDealInput(Deal deal) {
if (deal.getPrice() <= 0 || deal.getStartTime().isAfter(deal.getEndTime())) {
throw new IllegalArgumentException("Invalid deal details");
}
// Add more specific validation checks as needed
}
// Other methods
}
@RunWith(MockitoJUnitRunner.class)
public class DealServiceTest {
@Mock
private DealRepository dealRepository;
@Mock
private PurchaseHistoryRepository purchaseHistoryRepository;
@Mock
private InventoryService inventoryService;
@InjectMocks
private DealServiceImpl dealService;
@Test
public void testCreateDeal_WithValidDeal_ShouldCreateDeal() {
// Create a sample valid deal
Deal deal = new Deal();
deal.setPrice(100);
deal.setStartTime(LocalDateTime.now());
deal.setEndTime(LocalDateTime.now().plusHours(2));
// Mock repository behavior
when(dealRepository.save(any(Deal.class))).thenReturn(deal);
// Perform the service method
Deal createdDeal = dealService.createDeal(deal);
// Validate
assertNotNull(createdDeal);
assertEquals(100, createdDeal.getPrice());
// Add more assertions based on expected behavior
}
@Test(expected = IllegalArgumentException.class)
public void testCreateDeal_WithInvalidDeal_ShouldThrowException() {
// Create a sample invalid deal (start time after end time)
Deal invalidDeal = new Deal();
invalidDeal.setStartTime(LocalDateTime.now());
invalidDeal.setEndTime(LocalDateTime.now().minusHours(2));
// Perform the service method (this should throw an exception)
dealService.createDeal(invalidDeal);
}
// Add more test cases for other service methods
}
@Service
public class DealServiceImpl implements DealService {
// Other autowired components, repositories, and methods
@Override
@Transactional
public Deal createDeal(Deal deal) {
validateDealInput(deal); // This method validates the Deal input
try {
Deal createdDeal = dealRepository.save(deal);
inventoryService.decreaseItemStock(createdDeal.getItemId(), createdDeal.getItemsAvailable());
return createdDeal;
} catch (Exception e) {
LOGGER.error("Error occurred while creating deal: {}", e.getMessage());
throw new RuntimeException("Failed to create deal");
}
}
private void validateDealInput(Deal deal) {
// Implement input validation for Deal object
// For example, check if price, start time, and end time are valid
if (deal.getPrice() <= 0 || deal.getStartTime().isAfter(deal.getEndTime())) {
throw new IllegalArgumentException("Invalid deal details");
}
}
// Other methods
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
@RestController
public class DealController {
private final DealService dealService;
@Autowired
public DealController(DealService dealService) {
this.dealService = dealService;
}
@PostMapping("/deals")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Deal> createDeal(@RequestBody Deal deal) {
// Validate input deal
if (deal.getName() == null || deal.getName().isEmpty() || deal.getPrice() <= 0 || deal.getQuantity() <= 0) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// Save the deal to the database and return the created deal
deal.setStartTime(LocalDateTime.now());
deal.setEndTime(LocalDateTime.now().plusMinutes(deal.getDuration()));
return ResponseEntity.status(HttpStatus.CREATED).body(dealService.saveDeal(deal));
}
@PutMapping("/deals/{id}")
public ResponseEntity<Deal> updateDeal(@PathVariable int id, @RequestBody Deal updatedDeal) {
// Find the deal by ID and update the deal information
Deal deal = dealService.findDealById(id);
if (deal == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// Update the deal information and save to the database
deal.setName(updatedDeal.getName());
deal.setPrice(updatedDeal.getPrice());
deal.setQuantity(updatedDeal.getQuantity());
deal.setMaxClaimQuantity(updatedDeal.getMaxClaimQuantity());
deal.setEndTime(LocalDateTime.now().plusMinutes(updatedDeal.getDuration()));
return ResponseEntity.ok(dealService.saveDeal(deal));
}
@GetMapping("/deals/{id}")
public ResponseEntity<Deal> getDeal(@PathVariable int id) {
// Find the deal by ID
Deal deal = dealService.findDealById(id);
if (deal == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// Return the deal
return ResponseEntity.ok(deal);
}
@PostMapping("/deals/claim/{id}")
public ResponseEntity<Deal> claimDeal(@PathVariable int id, @RequestBody ClaimDealRequest claimDealRequest) {
// Find the deal by ID and validate if it's still active and if the user has not already claimed the deal
Deal deal = dealService.findDealById(id);
if (deal == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (deal.getEndTime().isBefore(LocalDateTime.now())) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (deal.getClaimQuantity() >= deal.getMaxClaimQuantity()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if (deal.getClaimedUsers().contains(claimDealRequest.getUserId())) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// Update the claimed quantity and user list and save to the database
deal.setClaimQuantity(deal.getClaimQuantity() + claimDealRequest.getQuantity());
deal.getClaimedUsers().add(claimDealRequest.getUserId());
dealService.saveDeal(deal);
// If the claimed quantity reaches the maximum allowed, end the deal
if (deal.getClaimQuantity() >= deal.getMaxClaimQuantity()) {
dealService.endDeal(deal.getId());
}
// Return the updated deal
return ResponseEntity.ok(deal);
}
@GetMapping("/deals/upcoming")
public ResponseEntity<List<Deal>> getUpcomingDeals() {
// Find all deals with a start time in the future
LocalDateTime now = LocalDateTime.now();
LocalDateTime twoHoursLater = now.plusHours(2);
List<Deal> upcomingDeals = dealService.findDealsByStartTimeBeforeAndEndTimeAfter(now, twoHoursLater);
return ResponseEntity.ok(upcomingDeals);
}
@GetMapping("/deals/ended")
public ResponseEntity<List<Deal>> getEndedDeals() {
// Find all deals with an end time in the past
LocalDateTime now = LocalDateTime.now();
List<Deal> endedDeals = dealService.findDealsByStartTimeBeforeAndEndTimeAfter(now, now);
return ResponseEntity.ok(endedDeals);
}
@GetMapping("/deals")
public ResponseEntity<List<Deal>> getAllDeals() {
// Find all deals
List<Deal> allDeals = dealService.findAllDeals();
return ResponseEntity.ok(allDeals);
}
}
@Service
public class DealServiceImpl implements DealService {
private static final Logger LOGGER = LoggerFactory.getLogger(DealServiceImpl.class);
@Autowired
private DealRepository dealRepository;
@Autowired
private PurchaseHistoryRepository purchaseHistoryRepository;
@Override
@Transactional
public Deal createDeal(Deal deal) {
validateDealInput(deal);
try {
return dealRepository.save(deal);
} catch (Exception e) {
LOGGER.error("Error occurred while creating deal: {}", e.getMessage());
throw new RuntimeException("Failed to create deal");
}
}
@Override
public boolean userAlreadyPurchased(Deal deal, int userId) {
return purchaseHistoryRepository.existsByUserIdAndDealId(userId, deal.getDealId());
}
@Override
@Transactional
public boolean buyDeal(int dealId, int userId) {
Deal deal = dealRepository.findById(dealId).orElse(null);
if (deal != null && canBuyDeal(deal, userId)) {
deal.setItemsSold(deal.getItemsSold() + 1);
dealRepository.save(deal);
return true;
}
return false;
}
private boolean canBuyDeal(Deal deal, int userId) {
LocalDateTime currentTime = LocalDateTime.now();
return currentTime.isBefore(deal.getEndTime()) &&
deal.getItemsSold() < deal.getItemsAvailable() &&
!userAlreadyPurchased(deal, userId);
}
private void validateDealInput(Deal deal) {
// Validation logic
}
}
@RestController
@RequestMapping("/deals")
public class DealController {
private final DealService dealService;
@Autowired
public DealController(DealService dealService) {
this.dealService = dealService;
}
@PostMapping
public ResponseEntity<Deal> createDeal(@RequestBody Deal deal) {
Deal createdDeal = dealService.createDeal(deal);
return ResponseEntity.ok(createdDeal);
}
@PostMapping("/{dealId}/buy")
public ResponseEntity<String> buyDeal(@PathVariable int dealId, @RequestParam int userId) {
boolean success = dealService.buyDeal(dealId, userId);
if (success) {
return ResponseEntity.ok("Deal purchased successfully");
} else {
return ResponseEntity.badRequest().body("Failed to purchase deal");
}
}
@PutMapping("/{dealId}")
public ResponseEntity<String> updateDeal(@PathVariable int dealId, @RequestBody Deal updatedDeal) {
Deal existingDeal = dealService.getDealById(dealId);
if (existingDeal != null) {
updatedDeal.setDealId(dealId); // Ensure the ID in the path matches the object
// Update fields of existingDeal with updatedDeal
dealService.updateDeal(existingDeal); // Implement logic to update the deal
return ResponseEntity.ok("Deal updated successfully");
} else {
return ResponseEntity.badRequest().body("Deal not found");
}
}
@DeleteMapping("/{dealId}")
public ResponseEntity<String> endDeal(@PathVariable int dealId) {
Deal existingDeal = dealService.getDealById(dealId);
if (existingDeal != null) {
dealService.endDeal(existingDeal); // Implement logic to end the deal
return ResponseEntity.ok("Deal ended successfully");
} else {
return ResponseEntity.badRequest().body("Deal not found");
}
}
// Other API endpoints for additional functionalities
}
@RunWith(MockitoJUnitRunner.class)
public class DealServiceTest {
@Mock
private DealRepository dealRepository;
@Mock
private PurchaseHistoryRepository purchaseHistoryRepository;
@Mock
private InventoryService inventoryService;
@InjectMocks
private DealServiceImpl dealService;
@Test
public void testCreateDeal_WithValidDeal_ShouldCreateDeal() {
// Implementation
}
@Test(expected = IllegalArgumentException.class)
public void testCreateDeal_WithInvalidDeal_ShouldThrowException() {
// Implementation
}
// Other test cases
}
Editor is loading...
Leave a Comment