Vendor Order Stacking made functional.

This commit is contained in:
Sidharth Prabhu
2026-04-20 14:13:17 +05:30
parent 149c579df6
commit 839343de14
4 changed files with 116 additions and 39 deletions

View File

@@ -183,12 +183,49 @@ public class ProductController {
public ResponseEntity<Product> publishProduct(@PathVariable Long id, @RequestBody Product productDetails) {
return productRepository.findById(id)
.map(product -> {
// Generate new PRD ID
String newProductId = "PRD-" + String.format("%04d", new java.util.Random().nextInt(10000));
String finalProductId = productDetails.getProductId();
// Update all details first
// If it's a draft ID or blank, try to find an existing live product by name first
if (finalProductId == null || finalProductId.startsWith("DRAFT-") || finalProductId.isEmpty()) {
List<Product> nameMatches = productRepository.findByNameRobust(productDetails.getName());
if (!nameMatches.isEmpty()) {
finalProductId = nameMatches.get(0).getProductId();
}
}
// If still a draft ID or blank, generate a new PRD ID
if (finalProductId == null || finalProductId.startsWith("DRAFT-") || finalProductId.isEmpty()) {
finalProductId = "PRD-" + String.format("%04d", new java.util.Random().nextInt(10000));
}
// Check if a live product with this ID already exists (to merge)
final String targetId = finalProductId;
java.util.Optional<Product> existingLive = productRepository.findByProductIdRobust(targetId);
if (existingLive.isPresent()) {
Product live = existingLive.get();
// MERGE: Update stock and other details
live.setStock((live.getStock() != null ? live.getStock() : 0) + (productDetails.getStock() != null ? productDetails.getStock() : 0));
live.setName(productDetails.getName());
live.setCategory(productDetails.getCategory());
live.setDescription(productDetails.getDescription());
live.setBasePrice(productDetails.getBasePrice());
live.setPrice(productDetails.getPrice());
live.setOfferPrice(productDetails.getOfferPrice());
live.setCounter(productDetails.getCounter());
live.setTag(productDetails.getTag());
live.setImageData(productDetails.getImageData());
live.setDraft(false);
live.setActive(true);
Product savedLive = productRepository.save(live);
productRepository.delete(product); // Delete the draft
updateStallAssociations(savedLive, productDetails.getStalls());
return ResponseEntity.ok(productRepository.findById(savedLive.getId()).orElse(savedLive));
} else {
// CREATE/UPDATE as new live product
product.setName(productDetails.getName());
product.setProductId(newProductId);
product.setProductId(finalProductId);
product.setCategory(productDetails.getCategory());
product.setDescription(productDetails.getDescription());
product.setBasePrice(productDetails.getBasePrice());
@@ -213,6 +250,7 @@ public class ProductController {
updateStallAssociations(updated, productDetails.getStalls());
return ResponseEntity.ok(productRepository.findById(updated.getId()).orElse(updated));
}
})
.orElse(ResponseEntity.notFound().build());
}

View File

@@ -25,6 +25,12 @@ public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByIsDraftTrue();
@Query("SELECT p FROM Product p WHERE LOWER(TRIM(p.name)) = LOWER(TRIM(:name)) AND (p.isDraft = false OR p.isDraft IS NULL)")
List<Product> findByNameRobust(@org.springframework.data.repository.query.Param("name") String name);
@Query("SELECT p FROM Product p WHERE p.productId = :productId AND (p.isDraft = false OR p.isDraft IS NULL)")
java.util.Optional<Product> findByProductIdRobust(@org.springframework.data.repository.query.Param("productId") String productId);
boolean existsByNameAndCategory(String name, String category);
@org.springframework.data.jpa.repository.Modifying
@org.springframework.data.jpa.repository.Query("UPDATE Product p SET p.stock = p.stock - :quantity WHERE p.id = :id AND p.stock >= :quantity")

View File

@@ -154,13 +154,31 @@ public class PurchaseService {
for (PurchaseOrderItem item : order.getItems()) {
Product draftProduct = new Product();
draftProduct.setName(item.getProductName());
// Try to find an existing live product with the same name to copy metadata
String itemName = item.getProductName();
List<Product> existingProducts = productRepository.findByNameRobust(itemName);
if (!existingProducts.isEmpty()) {
Product existing = existingProducts.get(0);
draftProduct.setCategory(existing.getCategory());
draftProduct.setImageData(existing.getImageData());
draftProduct.setDescription(existing.getDescription());
draftProduct.setTag(existing.getTag());
draftProduct.setCounter(existing.getCounter());
draftProduct.setPrice(existing.getPrice());
}
draftProduct.setStock(item.getQuantity() != null ? item.getQuantity().intValue() : 0);
draftProduct.setBasePrice(item.getRate());
draftProduct.setDraft(true);
draftProduct.setActive(false); // Not live yet
// Set a unique product ID if possible
if (!existingProducts.isEmpty()) {
draftProduct.setProductId(existingProducts.get(0).getProductId());
} else {
draftProduct.setProductId("DRAFT-" + String.format("%04d", new java.util.Random().nextInt(10000)) + "-" + item.getId());
}
productRepository.save(draftProduct);
}

View File

@@ -109,13 +109,29 @@ const Purchases: React.FC = () => {
};
const handleItemChange = (index: number, field: keyof PurchaseOrderItem, value: string | number) => {
const updatedItems = [...newOrder.items];
setNewOrder(prev => {
const updatedItems = [...prev.items];
const item = { ...updatedItems[index], [field]: value };
if (field === 'quantity' || field === 'rate') {
if (field === 'quantity' || field === 'rate' || field === 'productName') {
item.total = Number(item.quantity) * Number(item.rate);
}
updatedItems[index] = item;
setNewOrder({ ...newOrder, items: updatedItems });
return { ...prev, items: updatedItems };
});
};
const handleProductSelect = (index: number, product: any) => {
setNewOrder(prev => {
const updatedItems = [...prev.items];
updatedItems[index] = {
...updatedItems[index],
productName: product.name,
rate: product.basePrice || 0,
total: Number(updatedItems[index].quantity) * Number(product.basePrice || 0)
};
return { ...prev, items: updatedItems };
});
setActiveSearchIdx(null);
};
const calculateTotal = () => {
@@ -442,10 +458,9 @@ const Purchases: React.FC = () => {
<button
key={p.id}
type="button"
onClick={() => {
handleItemChange(idx, 'productName', p.name);
handleItemChange(idx, 'rate', p.basePrice || 0);
setActiveSearchIdx(null);
onMouseDown={(e) => {
e.preventDefault(); // Prevent focus loss
handleProductSelect(idx, p);
}}
className="w-full text-left px-4 py-3 hover:bg-indigo-50 flex flex-col transition-colors border-b border-[#f1f5f9] last:border-0"
>