Subversion Repositories SmartDukaan

Rev

Rev 34312 | Rev 34468 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33172 tejus.loha 1
package com.spice.profitmandi.service.order;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.BulkOrderModel;
33341 tejus.loha 5
import com.spice.profitmandi.common.model.LineItemModel;
33547 tejus.loha 6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
33341 tejus.loha 7
import com.spice.profitmandi.common.model.TransactionApprovalModel;
33172 tejus.loha 8
import com.spice.profitmandi.common.util.ExcelUtils;
34443 vikas.jang 9
import com.spice.profitmandi.common.util.Utils;
33172 tejus.loha 10
import com.spice.profitmandi.dao.cart.CartService;
33341 tejus.loha 11
import com.spice.profitmandi.dao.entity.auth.AuthUser;
34443 vikas.jang 12
import com.spice.profitmandi.dao.entity.catalog.Bid;
13
import com.spice.profitmandi.dao.entity.catalog.Liquidation;
33172 tejus.loha 14
import com.spice.profitmandi.dao.entity.catalog.TagListing;
34443 vikas.jang 15
import com.spice.profitmandi.dao.entity.dtr.User;
34312 ranu 16
import com.spice.profitmandi.dao.entity.transaction.*;
34443 vikas.jang 17
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
33213 tejus.loha 18
import com.spice.profitmandi.dao.enumuration.transaction.TransactionApprovalStatus;
33172 tejus.loha 19
import com.spice.profitmandi.dao.model.CartItem;
20
import com.spice.profitmandi.dao.model.UserCart;
33341 tejus.loha 21
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
33172 tejus.loha 22
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
34443 vikas.jang 23
import com.spice.profitmandi.dao.repository.cs.CsService;
33172 tejus.loha 24
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
33341 tejus.loha 25
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33338 amit.gupta 26
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
33213 tejus.loha 27
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
28
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
29
import com.spice.profitmandi.dao.repository.user.AddressRepository;
33338 amit.gupta 30
import com.spice.profitmandi.service.transaction.SDCreditService;
33172 tejus.loha 31
import com.spice.profitmandi.service.transaction.TransactionService;
32
import com.spice.profitmandi.service.wallet.CommonPaymentService;
33
import com.spice.profitmandi.service.wallet.WalletService;
34
import org.apache.logging.log4j.LogManager;
35
import org.apache.logging.log4j.Logger;
33213 tejus.loha 36
import org.apache.poi.ss.usermodel.Cell;
33172 tejus.loha 37
import org.apache.poi.ss.usermodel.Row;
38
import org.apache.poi.xssf.usermodel.XSSFRow;
39
import org.apache.poi.xssf.usermodel.XSSFSheet;
40
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
41
import org.springframework.beans.factory.annotation.Autowired;
34443 vikas.jang 42
import org.springframework.mail.javamail.JavaMailSender;
33213 tejus.loha 43
import org.springframework.stereotype.Service;
44
import org.springframework.transaction.annotation.Transactional;
33172 tejus.loha 45
import org.springframework.web.multipart.MultipartFile;
46
 
33338 amit.gupta 47
import java.math.BigDecimal;
33172 tejus.loha 48
import java.util.ArrayList;
49
import java.util.List;
50
import java.util.Map;
51
import java.util.stream.Collectors;
52
 
33213 tejus.loha 53
@Service
54
@Transactional(rollbackFor = Throwable.class)
33172 tejus.loha 55
public class BulkOrderService {
56
    private static final Logger LOGGER = LogManager.getLogger(BulkOrderService.class);
57
    @Autowired
58
    CartService cartService;
59
    @Autowired
60
    TransactionService transactionService;
61
    @Autowired
62
    CommonPaymentService commonPaymentService;
63
    @Autowired
64
    TagListingRepository tagListingRepository;
65
    @Autowired
66
    WalletService walletService;
67
    @Autowired
68
    UserRepository userRepository;
33213 tejus.loha 69
    @Autowired
70
    TransactionRepository transactionRepository;
71
    @Autowired
72
    TransactionApprovalRepository transactionApprovalRepository;
73
    @Autowired
74
    AddressRepository addressRepository;
33341 tejus.loha 75
    @Autowired
76
    OrderRepository orderRepository;
34443 vikas.jang 77
    //TODO:Tejus need to check
33341 tejus.loha 78
    @Autowired
79
    SDCreditRequirementRepository sdCreditRequirementRepository;
33338 amit.gupta 80
    @Autowired
81
    SDCreditService sdCreditService;
34443 vikas.jang 82
    @Autowired
83
    private CsService csService;
84
    @Autowired
85
    private JavaMailSender mailSender;
86
    @Autowired
87
    private AuthRepository authRepository;
33338 amit.gupta 88
 
89
 
34443 vikas.jang 90
    public void parseBulkOrders(MultipartFile file, int creatorId) throws Exception, ProfitMandiBusinessException {
33172 tejus.loha 91
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
92
 
93
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
94
        // Return first sheet from the XLSX workbook
95
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
96
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
97
        List<BulkOrderModel> bulkOrderModels = new ArrayList<>();
33547 tejus.loha 98
        LOGGER.info("mySheet.getLastRowNum() - {}", mySheet.getLastRowNum());
33172 tejus.loha 99
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
100
            XSSFRow row = mySheet.getRow(rowNumber);
33547 tejus.loha 101
            LOGGER.info("Row - {}", row);
102
            if (row != null) {
103
                BulkOrderModel bulkOrderModel = this.createBulkModel(row);
104
                bulkOrderModels.add(bulkOrderModel);
105
            } else {
106
                break;
107
            }
33172 tejus.loha 108
        }
34443 vikas.jang 109
        this.generatePurchaseOrder(bulkOrderModels, creatorId, ProfitMandiConstants.PO_TYPE.MANUAL);
110
    }
111
 
112
    public void generatePurchaseOrder(List<BulkOrderModel> bulkOrderModels, int creatorId, ProfitMandiConstants.PO_TYPE type) throws Exception,ProfitMandiBusinessException {
33172 tejus.loha 113
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
34443 vikas.jang 114
        boolean approvalRequired = false;
33172 tejus.loha 115
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
116
            int fofoId = fofoBulkOrderEntry.getKey();
117
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
118
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));
119
 
120
            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
121
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
122
            }
123
 
124
            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
125
            if (hasZeroQuantity) {
126
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
127
            }
128
 
129
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 130
            double totalPayableAmount = 0;
33172 tejus.loha 131
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
132
                CartItem cartItem = new CartItem();
133
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
134
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
135
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
33556 amit.gupta 136
                if (tagListing == null) {
137
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
138
                    throw new ProfitMandiBusinessException(message, message, message);
139
                }
33213 tejus.loha 140
                double itemSellingPrice = tagListing.getSellingPrice();
33597 tejus.loha 141
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
142
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33213 tejus.loha 143
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
144
                int itemId = cartItem.getItemId();
33597 tejus.loha 145
                if (isPriceZero || isActualPrice) {
33213 tejus.loha 146
                    cartItem.setSellingPrice(itemSellingPrice);
147
                } else {
33216 tejus.loha 148
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 149
                        cartItem.setSellingPrice(customSellingPrice);
34443 vikas.jang 150
                        approvalRequired = true;
33213 tejus.loha 151
 
152
                    } else {
153
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
154
                    }
155
 
156
                }
33338 amit.gupta 157
                totalPayableAmount += cartItem.getSellingPrice() * cartItem.getQuantity();
33172 tejus.loha 158
                cartItems.add(cartItem);
159
            }
33338 amit.gupta 160
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 161
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 162
 
163
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
164
 
165
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 166
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 167
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34443 vikas.jang 168
                if (type == ProfitMandiConstants.PO_TYPE.MANUAL) {
169
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");
170
                } else {
171
                    this.notifyPartnerRBM(netAmountInHand, totalPayableAmount, fofoId);
172
                }
33172 tejus.loha 173
            }
174
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 175
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 176
 
33351 amit.gupta 177
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 178
            int loanId = 0;
33547 tejus.loha 179
            if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34312 ranu 180
                Loan loan = sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 365, "Credit limit assigned via SD Credit");
181
                loanId = loan.getId();
33338 amit.gupta 182
            }
34443 vikas.jang 183
 
33338 amit.gupta 184
            int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
33213 tejus.loha 185
            //Set here created by
186
            Transaction transaction = transactionRepository.selectById(transactionId);
187
            transaction.setCreatedBy(creatorId);
188
            LOGGER.info("transaction  created by {}", transaction.getCreatedBy());
33172 tejus.loha 189
            commonPaymentService.payThroughWallet(transactionId);
34443 vikas.jang 190
            if (approvalRequired) {
191
                this.createApproval(transactionId);
192
            } else {
34312 ranu 193
                transactionService.processTransaction(transactionId,loanId);
33213 tejus.loha 194
            }
195
 
33172 tejus.loha 196
        }
197
    }
198
 
33213 tejus.loha 199
    public void createApproval(int transactionId) {
200
        TransactionApproval transactionApproval = new TransactionApproval();
201
        transactionApproval.setId(transactionId);
202
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
203
        transactionApprovalRepository.persist(transactionApproval);
204
    }
205
 
33172 tejus.loha 206
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
207
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
208
        int i = 0;
209
        bulkOrderModel.setRowIndex(row.getRowNum());
210
        try {
33696 amit.gupta 211
            Cell partnerName = row.getCell(i++);
212
            if (partnerName == null)
33213 tejus.loha 213
                bulkOrderModel.setPartnerName("");
214
            else
33696 amit.gupta 215
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 216
            Cell description = row.getCell(i++);
217
            if (description == null)
218
                bulkOrderModel.setDescription("");
219
            else
220
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
221
 
33172 tejus.loha 222
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
223
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 224
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 225
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
226
        } catch (Throwable e) {
227
            LOGGER.info(e.getCause());
33213 tejus.loha 228
            throw new ProfitMandiBusinessException("Field", "Field at row - " + row.getRowNum() + ", column - " + (i - 1), "Invalid field value at - " + ExcelUtils.toAlphabet(i - 1) + (row.getRowNum() + 1) + ", " + ExcelUtils.getCellValue(row.getCell(i - 1)));
33172 tejus.loha 229
        }
230
        LOGGER.info(bulkOrderModel);
231
        return bulkOrderModel;
232
    }
233
 
33341 tejus.loha 234
    // create model for transaction Approval so that finance team see all order and approve
235
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
236
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
237
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
238
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
239
        for (TransactionApproval transactionApproval : transactionApprovals) {
240
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
241
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
242
            List<LineItemModel> lineItemModelList = new ArrayList<>();
243
            for (Order order : orderList) {
244
                LineItem lineItem = order.getLineItem();
245
                LineItemModel lineItemModel = new LineItemModel();
246
                lineItemModel.setItemId(lineItem.getItemId());
247
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
248
                lineItemModel.setItemQuantity(lineItem.getQuantity());
249
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
250
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
251
                lineItemModelList.add(lineItemModel);
252
            }
253
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
254
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
255
            String retailerName = " ";
256
            retailerName = orderList.get(0).getRetailerName();
257
            transactionApprovalModel.setRetailerName(retailerName);
258
            transactionApprovalModel.setCreatedBy(authUser.getFullName());
259
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
260
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
261
            transactionApprovalModel.setLineItemModels(lineItemModelList);
262
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 263
 
33341 tejus.loha 264
        }
265
        return approvalModelList;
266
    }
267
 
34443 vikas.jang 268
    public void notifyPartnerRBM(double netAmountInHand, double totalPayableAmount, int fofoId) throws Exception, ProfitMandiBusinessException {
269
        User user = userRepository.selectById(fofoId);
270
        int rbmId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
271
        AuthUser authUser = authRepository.selectById(rbmId);
33341 tejus.loha 272
 
34443 vikas.jang 273
        //String[] emailTo = new String[] { authUser.getEmailId() };
274
        String[] emailTo = new String[] { "vjangra856@gmail.com" };
275
 
276
        String[] ccTo = {"vikas.jangra@smartdukaan.com"};
277
        String subject = "Dispatch On Hold(Bidding)";
278
        String message = String.format(
279
                "Dear Team, \n"
280
                        + "This is to inform you that the material for %s with the value Rs.%s "
281
                        + "purchase is hold till the money against the stock will receive. Kindly inform the partner "
282
                        + "about wallet topup with amount of Rs.%s. The material will be dispatched.",
283
                user.getFirstName(), totalPayableAmount, (totalPayableAmount - netAmountInHand)
284
        );
285
 
286
        LOGGER.info("mailMessage: {}",message);
287
        Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
288
    }
289
 
290
 
33172 tejus.loha 291
}