Subversion Repositories SmartDukaan

Rev

Rev 35956 | Rev 35995 | 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;
35971 aman 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;
34832 ranu 13
import com.spice.profitmandi.dao.entity.catalog.Item;
33172 tejus.loha 14
import com.spice.profitmandi.dao.entity.catalog.TagListing;
34856 ranu 15
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
34566 ranu 16
import com.spice.profitmandi.dao.entity.fofo.LoanTransaction;
34674 aman.kumar 17
import com.spice.profitmandi.dao.entity.transaction.LineItem;
18
import com.spice.profitmandi.dao.entity.transaction.Order;
19
import com.spice.profitmandi.dao.entity.transaction.Transaction;
20
import com.spice.profitmandi.dao.entity.transaction.TransactionApproval;
35971 aman 21
import com.spice.profitmandi.dao.entity.user.StoreTimelinetb;
22
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
23
import com.spice.profitmandi.dao.enumuration.dtr.StoreTimeline;
33213 tejus.loha 24
import com.spice.profitmandi.dao.enumuration.transaction.TransactionApprovalStatus;
33172 tejus.loha 25
import com.spice.profitmandi.dao.model.CartItem;
26
import com.spice.profitmandi.dao.model.UserCart;
33341 tejus.loha 27
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
34468 vikas.jang 28
import com.spice.profitmandi.dao.repository.catalog.BidRepository;
34832 ranu 29
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
34468 vikas.jang 30
import com.spice.profitmandi.dao.repository.catalog.LiquidationRepository;
33172 tejus.loha 31
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
34443 vikas.jang 32
import com.spice.profitmandi.dao.repository.cs.CsService;
34856 ranu 33
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33172 tejus.loha 34
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
34566 ranu 35
import com.spice.profitmandi.dao.repository.fofo.LoanTransactionRepository;
33341 tejus.loha 36
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33338 amit.gupta 37
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
33213 tejus.loha 38
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
39
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
40
import com.spice.profitmandi.dao.repository.user.AddressRepository;
34468 vikas.jang 41
import com.spice.profitmandi.dao.service.BidService;
34832 ranu 42
import com.spice.profitmandi.service.catalog.BrandsService;
34661 ranu 43
import com.spice.profitmandi.service.transaction.BlockLoanIdSanctionId;
33338 amit.gupta 44
import com.spice.profitmandi.service.transaction.SDCreditService;
33172 tejus.loha 45
import com.spice.profitmandi.service.transaction.TransactionService;
46
import com.spice.profitmandi.service.wallet.CommonPaymentService;
47
import com.spice.profitmandi.service.wallet.WalletService;
48
import org.apache.logging.log4j.LogManager;
49
import org.apache.logging.log4j.Logger;
33213 tejus.loha 50
import org.apache.poi.ss.usermodel.Cell;
33172 tejus.loha 51
import org.apache.poi.ss.usermodel.Row;
52
import org.apache.poi.xssf.usermodel.XSSFRow;
53
import org.apache.poi.xssf.usermodel.XSSFSheet;
54
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
55
import org.springframework.beans.factory.annotation.Autowired;
35971 aman 56
import org.springframework.mail.javamail.JavaMailSender;
33213 tejus.loha 57
import org.springframework.stereotype.Service;
33172 tejus.loha 58
import org.springframework.web.multipart.MultipartFile;
59
 
33338 amit.gupta 60
import java.math.BigDecimal;
35956 amit 61
import java.time.LocalDateTime;
33172 tejus.loha 62
import java.util.ArrayList;
63
import java.util.List;
64
import java.util.Map;
35690 amit 65
import java.util.Set;
33172 tejus.loha 66
import java.util.stream.Collectors;
67
 
33213 tejus.loha 68
@Service
33172 tejus.loha 69
public class BulkOrderService {
70
    private static final Logger LOGGER = LogManager.getLogger(BulkOrderService.class);
71
    @Autowired
72
    CartService cartService;
73
    @Autowired
74
    TransactionService transactionService;
75
    @Autowired
76
    CommonPaymentService commonPaymentService;
77
    @Autowired
78
    TagListingRepository tagListingRepository;
79
    @Autowired
80
    WalletService walletService;
81
    @Autowired
82
    UserRepository userRepository;
33213 tejus.loha 83
    @Autowired
84
    TransactionRepository transactionRepository;
85
    @Autowired
86
    TransactionApprovalRepository transactionApprovalRepository;
87
    @Autowired
88
    AddressRepository addressRepository;
33341 tejus.loha 89
    @Autowired
90
    OrderRepository orderRepository;
34443 vikas.jang 91
    //TODO:Tejus need to check
33341 tejus.loha 92
    @Autowired
93
    SDCreditRequirementRepository sdCreditRequirementRepository;
33338 amit.gupta 94
    @Autowired
95
    SDCreditService sdCreditService;
34443 vikas.jang 96
    @Autowired
97
    private CsService csService;
98
    @Autowired
34468 vikas.jang 99
    private AuthRepository authRepository;
34443 vikas.jang 100
    @Autowired
34468 vikas.jang 101
    private BidRepository bidRepository;
102
    @Autowired
103
    private BidService bidService;
104
    @Autowired
34832 ranu 105
    ItemRepository itemRepository;
106
    @Autowired
107
    private BrandsService brandsService;
108
    @Autowired
34566 ranu 109
    private LoanTransactionRepository loanTransactionRepository;
110
 
111
    @Autowired
34468 vikas.jang 112
    private LiquidationRepository liquidationRepository;
33338 amit.gupta 113
 
34674 aman.kumar 114
    @Autowired
115
    com.spice.profitmandi.dao.repository.user.UserRepository user_userRepository;
33338 amit.gupta 116
 
34856 ranu 117
    @Autowired
118
    FofoStoreRepository fofoStoreRepository;
34674 aman.kumar 119
 
35971 aman 120
    @Autowired
121
    JavaMailSender mailSender;
34856 ranu 122
 
35971 aman 123
    @Autowired
124
    com.spice.profitmandi.service.user.StoreTimelineTatService storeTimelineTatService;
125
 
126
    @Autowired
127
    com.spice.profitmandi.dao.repository.dtr.PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
128
 
129
    @Autowired
130
    com.spice.profitmandi.dao.repository.user.StoreTimelinetbRepository storeTimelinetbRepository;
131
 
132
 
34468 vikas.jang 133
    public void parseBulkOrders(MultipartFile file, int creatorId) throws Exception {
33172 tejus.loha 134
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
135
 
136
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
137
        // Return first sheet from the XLSX workbook
138
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
139
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
140
        List<BulkOrderModel> bulkOrderModels = new ArrayList<>();
33547 tejus.loha 141
        LOGGER.info("mySheet.getLastRowNum() - {}", mySheet.getLastRowNum());
33172 tejus.loha 142
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
143
            XSSFRow row = mySheet.getRow(rowNumber);
33547 tejus.loha 144
            LOGGER.info("Row - {}", row);
145
            if (row != null) {
146
                BulkOrderModel bulkOrderModel = this.createBulkModel(row);
147
                bulkOrderModels.add(bulkOrderModel);
148
            } else {
149
                break;
150
            }
33172 tejus.loha 151
        }
34468 vikas.jang 152
        this.generatePurchaseOrder(bulkOrderModels, creatorId, ProfitMandiConstants.PO_TYPE.MANUAL, ProfitMandiConstants.BID_CRON_ENUM.TODAY);
34443 vikas.jang 153
    }
154
 
34592 vikas.jang 155
    public ProfitMandiConstants.BID_ENUM generatePurchaseOrder(List<BulkOrderModel> bulkOrderModels, int creatorId, ProfitMandiConstants.PO_TYPE type, ProfitMandiConstants.BID_CRON_ENUM scheduleType) throws Exception {
33172 tejus.loha 156
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
34443 vikas.jang 157
        boolean approvalRequired = false;
34592 vikas.jang 158
        ProfitMandiConstants.BID_ENUM finalBidStatus = ProfitMandiConstants.BID_ENUM.CLOSED;
33172 tejus.loha 159
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
160
            int fofoId = fofoBulkOrderEntry.getKey();
161
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
162
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));
163
 
164
            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
165
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
166
            }
167
 
168
            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
169
            if (hasZeroQuantity) {
170
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
171
            }
172
 
35690 amit 173
            // Batch-fetch per-fofo data once (instead of per-item)
174
            FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
175
            List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
176
 
177
            // Batch-fetch items and tag listings for all items in this fofo's order (2 queries instead of 2N)
178
            Set<Integer> allItemIds = fofoBulkOrderModels.stream().map(BulkOrderModel::getItemId).collect(Collectors.toSet());
179
            Map<Integer, TagListing> tagListingMap = tagListingRepository.selectByItemIds(allItemIds);
180
            Map<Integer, Item> itemMap = itemRepository.selectByIds(allItemIds).stream()
181
                    .collect(Collectors.toMap(Item::getId, item -> item));
182
 
33172 tejus.loha 183
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 184
            double totalPayableAmount = 0;
34957 amit 185
            BigDecimal totalPayableAmountBD = new BigDecimal(0);
33172 tejus.loha 186
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
187
                CartItem cartItem = new CartItem();
188
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
189
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
35690 amit 190
                TagListing tagListing = tagListingMap.get(fofoBulkOrderModel.getItemId());
33556 amit.gupta 191
                if (tagListing == null) {
192
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
193
                    throw new ProfitMandiBusinessException(message, message, message);
194
                }
35690 amit 195
                Item item = itemMap.get(fofoBulkOrderModel.getItemId());
196
                if (item == null) {
197
                    throw new ProfitMandiBusinessException("Item not found", fofoBulkOrderModel.getItemId(), "Item does not exist: " + fofoBulkOrderModel.getItemId());
198
                }
34856 ranu 199
                if (!fofoStore.isInternal()) {
200
                    if (partnerIneligibleBrands.contains(item.getBrand())) {
201
                        throw new ProfitMandiBusinessException("Brand is not allowed", "Brand ( " + item.getBrand() + ") is not allowed for this partner", "");
202
                    }
34832 ranu 203
                }
204
 
33213 tejus.loha 205
                double itemSellingPrice = tagListing.getSellingPrice();
33597 tejus.loha 206
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
207
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33213 tejus.loha 208
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
209
                int itemId = cartItem.getItemId();
33597 tejus.loha 210
                if (isPriceZero || isActualPrice) {
33213 tejus.loha 211
                    cartItem.setSellingPrice(itemSellingPrice);
212
                } else {
33216 tejus.loha 213
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 214
                        cartItem.setSellingPrice(customSellingPrice);
34443 vikas.jang 215
                        approvalRequired = true;
33213 tejus.loha 216
 
217
                    } else {
218
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
219
                    }
220
 
221
                }
34958 amit 222
                totalPayableAmountBD = totalPayableAmountBD.add(new BigDecimal(String.valueOf(cartItem.getSellingPrice())).multiply(new BigDecimal(cartItem.getQuantity())));
33172 tejus.loha 223
                cartItems.add(cartItem);
224
            }
34957 amit 225
            totalPayableAmount = totalPayableAmountBD.doubleValue();
34501 vikas.jang 226
            Bid bid = null;
227
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
228
                bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
34592 vikas.jang 229
                approvalRequired = false;
34957 amit 230
                totalPayableAmount = totalPayableAmountBD.doubleValue() - ProfitMandiConstants.BID_CHARGES;
34501 vikas.jang 231
            }
33338 amit.gupta 232
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 233
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 234
 
235
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
236
 
237
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 238
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 239
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 240
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34695 aman.kumar 241
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, String.valueOf(fofoId));
34443 vikas.jang 242
                } else {
34468 vikas.jang 243
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
34592 vikas.jang 244
                        finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 245
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Sending mail to RBM");
246
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
34468 vikas.jang 247
                    } else {
34592 vikas.jang 248
                        finalBidStatus = bidService.cancelYesterdayProcessBid(bid);
34572 vikas.jang 249
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
250
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
34468 vikas.jang 251
                    }
34443 vikas.jang 252
                }
33172 tejus.loha 253
            }
254
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 255
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 256
 
33351 amit.gupta 257
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 258
            int loanId = 0;
34492 vikas.jang 259
            try {
260
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34576 vikas.jang 261
                    LOGGER.info("Creating new loan for: {}",userCart.getUserId());
34675 aman.kumar 262
                    BlockLoanIdSanctionId loan = sdCreditService.createSDDirectOrder(userCart.getUserId(), totalPayableAmount, 0);
34661 ranu 263
                    loanId = loan.getLoanId();
34492 vikas.jang 264
                }
265
            } catch (Exception exception){
34501 vikas.jang 266
                if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
34592 vikas.jang 267
                    finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 268
                    LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
269
                    //throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
34501 vikas.jang 270
                }
33338 amit.gupta 271
            }
34443 vikas.jang 272
 
34576 vikas.jang 273
            LOGGER.info("finalBidStatus: {}",finalBidStatus);
34573 vikas.jang 274
            if (finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CLOSED)) {
35971 aman 275
                // Check if this is the first PO for this partner (before creating the new transaction)
276
                List<Transaction> existingTransactions = transactionRepository.selectByRetailerId(fofoId);
277
                boolean isFirstPO = (existingTransactions == null || existingTransactions.isEmpty());
278
 
279
                // Block first PO if FULL_STOCK_PAYMENT is not done (for LOI-flow partners only)
280
                if (isFirstPO && fofoStore != null && !fofoStore.isInternal() && fofoStore.getCode() != null) {
281
                    com.spice.profitmandi.dao.entity.fofo.PartnerOnBoardingPanel pob =
282
                            partnerOnBoardingPanelRepository.selectByCode(fofoStore.getCode());
283
                    if (pob != null) {
284
                        StoreTimelinetb fspEntry = storeTimelinetbRepository.selectByOnboardingIdAndEvent(
285
                                pob.getId(), StoreTimeline.FULL_STOCK_PAYMENT);
286
                        if (fspEntry == null) {
287
                            LOGGER.warn("PO creation blocked for fofoId={}, onboardingId={}: FULL_STOCK_PAYMENT not done", fofoId, pob.getId());
288
                            throw new ProfitMandiBusinessException(
289
                                    "Full Stock Payment is required before creating PO",
290
                                    fofoStore.getCode(),
291
                                    "Full Stock Payment must be completed before first PO can be created");
292
                        }
293
                    }
294
                }
295
 
34959 amit 296
                LOGGER.info("totalPayableAmount - {}", totalPayableAmount);
34573 vikas.jang 297
                int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
298
                //Set here created by
299
                Transaction transaction = transactionRepository.selectById(transactionId);
300
                transaction.setCreatedBy(creatorId);
34637 vikas.jang 301
                LOGGER.info("transaction created by {}", transaction.getCreatedBy());
34573 vikas.jang 302
                commonPaymentService.payThroughWallet(transactionId);
303
                if (approvalRequired) {
304
                    this.createApproval(transactionId);
305
                    if (loanId > 0) {
306
                        LoanTransaction loanTransaction = new LoanTransaction();
307
                        loanTransaction.setLoanId(loanId);
308
                        loanTransaction.setTransactionId(transactionId);
309
                        loanTransactionRepository.persist(loanTransaction);
310
                    }
311
                } else {
312
                    transactionService.processTransaction(transactionId, loanId);
313
                }
35971 aman 314
 
315
                // Send approval email to Sales L3 only for first PO
316
                if (isFirstPO) {
317
                    try {
318
                        sendFirstPOApprovalEmail(fofoStore, transactionId, totalPayableAmount, creatorId);
319
                    } catch (Exception e) {
320
                        LOGGER.error("Failed to send first PO approval email for fofoId: " + fofoId, e);
321
                    }
322
                    // Track PO_CREATION on timeline for first PO
323
                    try {
324
                        if (fofoStore != null && fofoStore.getCode() != null) {
325
                            com.spice.profitmandi.dao.entity.fofo.PartnerOnBoardingPanel pob =
326
                                    partnerOnBoardingPanelRepository.selectByCode(fofoStore.getCode());
327
                            if (pob != null) {
328
                                storeTimelineTatService.onPoCreationComplete(pob.getId());
329
                                // If no approval required, PO is auto-approved
330
                                if (!approvalRequired) {
331
                                    storeTimelineTatService.onPoApprovalComplete(pob.getId());
332
                                }
333
                            }
334
                        }
335
                    } catch (Exception e) {
336
                        LOGGER.error("Failed to track PO_CREATION timeline for fofoId: " + fofoId, e);
337
                    }
338
                }
33213 tejus.loha 339
            }
340
 
33172 tejus.loha 341
        }
34592 vikas.jang 342
        return finalBidStatus;
33172 tejus.loha 343
    }
344
 
33213 tejus.loha 345
    public void createApproval(int transactionId) {
346
        TransactionApproval transactionApproval = new TransactionApproval();
347
        transactionApproval.setId(transactionId);
348
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
349
        transactionApprovalRepository.persist(transactionApproval);
350
    }
351
 
33172 tejus.loha 352
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
353
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
354
        int i = 0;
355
        bulkOrderModel.setRowIndex(row.getRowNum());
356
        try {
33696 amit.gupta 357
            Cell partnerName = row.getCell(i++);
358
            if (partnerName == null)
33213 tejus.loha 359
                bulkOrderModel.setPartnerName("");
360
            else
33696 amit.gupta 361
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 362
            Cell description = row.getCell(i++);
363
            if (description == null)
364
                bulkOrderModel.setDescription("");
365
            else
366
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
367
 
33172 tejus.loha 368
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
369
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 370
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 371
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
372
        } catch (Throwable e) {
373
            LOGGER.info(e.getCause());
33213 tejus.loha 374
            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 375
        }
376
        LOGGER.info(bulkOrderModel);
377
        return bulkOrderModel;
378
    }
379
 
33341 tejus.loha 380
    // create model for transaction Approval so that finance team see all order and approve
381
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
382
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
383
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
384
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
385
        for (TransactionApproval transactionApproval : transactionApprovals) {
386
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
387
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
388
            List<LineItemModel> lineItemModelList = new ArrayList<>();
389
            for (Order order : orderList) {
390
                LineItem lineItem = order.getLineItem();
391
                LineItemModel lineItemModel = new LineItemModel();
392
                lineItemModel.setItemId(lineItem.getItemId());
393
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
394
                lineItemModel.setItemQuantity(lineItem.getQuantity());
395
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
396
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
397
                lineItemModelList.add(lineItemModel);
398
            }
399
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
400
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
401
            String retailerName = " ";
402
            retailerName = orderList.get(0).getRetailerName();
403
            transactionApprovalModel.setRetailerName(retailerName);
34573 vikas.jang 404
            if (authUser == null) {
405
                transactionApprovalModel.setCreatedBy(retailerName);
406
            } else {
407
                transactionApprovalModel.setCreatedBy(authUser.getFullName());
408
            }
33341 tejus.loha 409
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
410
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
411
            transactionApprovalModel.setLineItemModels(lineItemModelList);
412
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 413
 
33341 tejus.loha 414
        }
415
        return approvalModelList;
416
    }
417
 
35956 amit 418
    public List<TransactionApprovalModel> getBulkOrderApprovalReport(LocalDateTime startDate, LocalDateTime endDate) throws ProfitMandiBusinessException {
419
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllByDateRange(startDate, endDate);
420
        LOGGER.info("Approval report: found {} records", transactionApprovals.size());
421
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
422
        for (TransactionApproval transactionApproval : transactionApprovals) {
423
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
424
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
425
            List<LineItemModel> lineItemModelList = new ArrayList<>();
426
            for (Order order : orderList) {
427
                LineItem lineItem = order.getLineItem();
428
                LineItemModel lineItemModel = new LineItemModel();
429
                lineItemModel.setItemId(lineItem.getItemId());
430
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
431
                lineItemModel.setItemQuantity(lineItem.getQuantity());
432
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
433
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
434
                lineItemModelList.add(lineItemModel);
435
            }
436
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
437
            TransactionApprovalModel model = new TransactionApprovalModel();
438
            String retailerName = orderList.isEmpty() ? "" : orderList.get(0).getRetailerName();
439
            model.setRetailerName(retailerName);
440
            if (authUser == null) {
441
                model.setCreatedBy(retailerName);
442
            } else {
443
                model.setCreatedBy(authUser.getFullName());
444
            }
445
            model.setCreatedOn(transaction.getCreateTimestamp());
446
            model.setTransactionId(transactionApproval.getId());
447
            model.setLineItemModels(lineItemModelList);
448
            model.setStatus(transactionApproval.getStatus().name());
449
            model.setApprovedBy(transactionApproval.getApprovedBy());
450
            model.setApprovedOn(transactionApproval.getApprovedOn());
451
            model.setRemark(transactionApproval.getRemark());
452
            approvalModelList.add(model);
453
        }
454
        return approvalModelList;
455
    }
456
 
35971 aman 457
    private void sendFirstPOApprovalEmail(FofoStore fofoStore, int transactionId, double totalAmount, int creatorId) throws Exception {
458
        String partnerName = "Partner";
459
        if (fofoStore.getUserAddress() != null && fofoStore.getUserAddress().getName() != null) {
460
            partnerName = fofoStore.getUserAddress().getName();
461
        }
462
        String storeCode = fofoStore.getCode() != null ? fofoStore.getCode() : "";
463
 
464
        String createdByName = "";
465
        if (creatorId > 0) {
466
            AuthUser creator = authRepository.selectById(creatorId);
467
            if (creator != null) {
468
                createdByName = creator.getFullName();
469
            }
470
        }
471
 
472
        String subject = "First PO Created - Approval Required - " + partnerName + " (" + storeCode + ")";
473
 
474
        StringBuilder sb = new StringBuilder();
475
        sb.append("<html><body>");
476
        sb.append("<p>Dear Team,</p>");
477
        sb.append("<p>The <strong>first Purchase Order</strong> has been created for the below partner. Please review and approve.</p><br/>");
478
        sb.append("<table style='border:1px solid black; border-collapse: collapse;'>");
479
        sb.append("<tbody>");
480
        sb.append("<tr>");
481
        sb.append("<th style='border:1px solid black; padding: 5px;'>Partner Name</th>");
482
        sb.append("<th style='border:1px solid black; padding: 5px;'>Store Code</th>");
483
        sb.append("<th style='border:1px solid black; padding: 5px;'>Transaction ID</th>");
484
        sb.append("<th style='border:1px solid black; padding: 5px;'>Total Amount</th>");
485
        sb.append("<th style='border:1px solid black; padding: 5px;'>Created By</th>");
486
        sb.append("</tr>");
487
        sb.append("<tr>");
488
        sb.append("<td style='border:1px solid black; padding: 5px;'>").append(partnerName).append("</td>");
489
        sb.append("<td style='border:1px solid black; padding: 5px;'>").append(storeCode).append("</td>");
490
        sb.append("<td style='border:1px solid black; padding: 5px;'>").append(transactionId).append("</td>");
491
        sb.append("<td style='border:1px solid black; padding: 5px;'>").append(String.format("%.2f", totalAmount)).append("</td>");
492
        sb.append("<td style='border:1px solid black; padding: 5px;'>").append(createdByName).append("</td>");
493
        sb.append("</tr>");
494
        sb.append("</tbody></table>");
495
        sb.append("<br/><p>Please approve this order from the <strong>Transaction Approvals</strong> panel.</p>");
496
        sb.append("<br/><p>Regards,<br/>Smart Dukaan</p>");
497
        sb.append("</body></html>");
498
 
499
        // Send to Sales L3
500
        List<AuthUser> salesL3Users = csService.getAuthUserByCategoryId(
501
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L3);
502
 
503
        List<String> sendTo = new ArrayList<>();
504
        if (!salesL3Users.isEmpty()) {
505
            sendTo.addAll(salesL3Users.stream().map(AuthUser::getEmailId).collect(Collectors.toList()));
506
        }
507
 
508
        if (!sendTo.isEmpty()) {
509
            String[] emailArray = sendTo.toArray(new String[0]);
510
            Utils.sendMailWithAttachments(mailSender, emailArray, null, subject, sb.toString());
511
            LOGGER.info("First PO approval email sent for fofoId: {} transactionId: {}", fofoStore.getId(), transactionId);
512
        }
513
    }
514
 
33172 tejus.loha 515
}