package devopsdistilled.operp.server.data.service.business.impl;

import java.util.Date;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import devopsdistilled.operp.server.data.entity.account.PaidTransaction;
import devopsdistilled.operp.server.data.entity.business.Purchase;
import devopsdistilled.operp.server.data.repo.business.PurchaseRepository;
import devopsdistilled.operp.server.data.service.account.PaidTransactionService;
import devopsdistilled.operp.server.data.service.business.PurchaseService;

@Service
public class PurchaseServiceImpl extends
		BusinessServiceImpl<Purchase, PurchaseRepository> implements
		PurchaseService {

	private static final long serialVersionUID = 2688393943868408691L;

	@Inject
	private PurchaseRepository repo;

	@Inject
	private PaidTransactionService paidTransactionService;

	@Override
	protected PurchaseRepository getRepo() {
		return repo;
	}

	@Override
	@Transactional
	public <S extends Purchase> S save(S purchase) {
		purchase.setDate(new Date());
		S savedPurchase = super.save(purchase);

		PaidTransaction transaction = new PaidTransaction();
		transaction.setAccount(savedPurchase.getParty().getAccount());
		transaction.setNote("From Purchase #"
				+ savedPurchase.getBusinessId().toString() + " on "
				+ savedPurchase.getDate());
		transaction.setAmount(savedPurchase.getAmount() * (-1));
		paidTransactionService.save(transaction);
		return savedPurchase;

	}
}

@@ -365,16 +365,218 @@
 rchase;%0A
+import devopsdistilled.operp.server.data.entity.business.PurchaseDescRow;%0Aimport devopsdistilled.operp.server.data.entity.stock.Stock;%0Aimport devopsdistilled.operp.server.data.entity.stock.StockKeeper;%0A
 import d
@@ -642,16 +642,16 @@
 sitory;%0A
-
 import d
@@ -797,16 +797,91 @@
 Service;
+%0Aimport devopsdistilled.operp.server.data.service.stock.StockKeeperService;
 %0A%0A@Servi
@@ -1187,16 +1187,74 @@
 rvice;%0A%0A
+%09@Inject%0A%09private StockKeeperService stockKeeperService;%0A%0A
 %09@Overri
@@ -1426,16 +1426,16 @@
 ate());%0A
-
 %09%09S save
@@ -1469,16 +1469,545 @@
 hase);%0A%0A
+%09%09for (PurchaseDescRow purchaseDescRow : savedPurchase.getBusinessDesc()%0A%09%09%09%09.getDescRows()) %7B%0A%0A%09%09%09Stock stock = new Stock();%0A%09%09%09stock.setItem(purchaseDescRow.getItem());%0A%09%09%09stock.setWarehouse(purchaseDescRow.getWarehouse());%0A%0A%09%09%09StockKeeper stockKeeper = new StockKeeper();%0A%09%09%09stockKeeper.setStock(stock);%0A%09%09%09stockKeeper.setQuantity(purchaseDescRow.getQuantity());%0A%09%09%09stockKeeper.setNote(%22From Purchase #%22 + purchase.getBusinessId());%0A%09%09%09stockKeeper.setStockUpdateDate(new Date());%0A%09%09%09stockKeeperService.save(stockKeeper);%0A%09%09%7D%0A%0A
 %09%09PaidTr

Update stock on purchase