Subversion Repositories SmartDukaan

Rev

Rev 35957 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
23405 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
30046 tejbeer 3
import com.spice.profitmandi.common.enumuration.ActivationType;
23785 amit.gupta 4
import com.spice.profitmandi.common.enumuration.CounterSize;
26846 tejbeer 5
import com.spice.profitmandi.common.enumuration.MessageType;
23405 amit.gupta 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30017 amit.gupta 7
import com.spice.profitmandi.common.model.*;
24231 amit.gupta 8
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 9
import com.spice.profitmandi.common.util.Utils.Attachment;
34490 ranu 10
import com.spice.profitmandi.common.web.util.ResponseSender;
35957 amit 11
import com.spice.profitmandi.service.mail.MailOutboxService;
26721 tejbeer 12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
35236 amit 13
import com.spice.profitmandi.dao.entity.catalog.*;
27088 tejbeer 14
import com.spice.profitmandi.dao.entity.cs.Region;
30017 amit.gupta 15
import com.spice.profitmandi.dao.entity.fofo.*;
30664 amit.gupta 16
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
30003 tejbeer 17
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
33812 tejus.loha 18
import com.spice.profitmandi.dao.entity.transaction.Loan;
23796 amit.gupta 19
import com.spice.profitmandi.dao.entity.transaction.Order;
34397 ranu 20
import com.spice.profitmandi.dao.entity.transaction.SDCreditRequirement;
35811 amit 21
import com.spice.profitmandi.dao.model.BulkCreditSummary;
22
import com.spice.profitmandi.service.transaction.SDCreditService;
26846 tejbeer 23
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
30017 amit.gupta 24
import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;
26978 tejbeer 25
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
35765 ranu 26
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
27
import com.spice.profitmandi.dao.event.TagListingEventPublisher;
34389 ranu 28
import com.spice.profitmandi.dao.model.*;
26721 tejbeer 29
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
35765 ranu 30
import com.spice.profitmandi.dao.repository.catalog.*;
31663 amit.gupta 31
import com.spice.profitmandi.dao.repository.cs.*;
30044 tejbeer 32
import com.spice.profitmandi.dao.repository.dtr.BrandLimitRepository;
23779 amit.gupta 33
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 34
import com.spice.profitmandi.dao.repository.dtr.Mongo;
26846 tejbeer 35
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
30017 amit.gupta 36
import com.spice.profitmandi.dao.repository.fofo.*;
30664 amit.gupta 37
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
27768 tejbeer 38
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
30017 amit.gupta 39
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
33812 tejus.loha 40
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
23796 amit.gupta 41
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
34397 ranu 42
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
23796 amit.gupta 43
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
44
import com.spice.profitmandi.dao.repository.user.UserRepository;
30017 amit.gupta 45
import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;
35765 ranu 46
import com.spice.profitmandi.model.WarehouseItemQtyModel;
34397 ranu 47
import com.spice.profitmandi.service.FofoUser;
26846 tejbeer 48
import com.spice.profitmandi.service.NotificationService;
34397 ranu 49
import com.spice.profitmandi.service.RbmTargetService;
23798 amit.gupta 50
import com.spice.profitmandi.service.authentication.RoleManager;
34513 ranu 51
import com.spice.profitmandi.service.catalog.BrandsService;
34035 ranu 52
import com.spice.profitmandi.service.inventory.*;
23779 amit.gupta 53
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 54
import com.spice.profitmandi.service.wallet.WalletService;
23405 amit.gupta 55
import com.spice.profitmandi.web.model.LoginDetails;
56
import com.spice.profitmandi.web.util.CookiesProcessor;
57
import com.spice.profitmandi.web.util.MVCResponseSender;
33910 amit.gupta 58
import in.shop2020.model.v1.order.OrderStatus;
30017 amit.gupta 59
import org.apache.commons.io.output.ByteArrayOutputStream;
60
import org.apache.logging.log4j.LogManager;
61
import org.apache.logging.log4j.Logger;
62
import org.json.JSONArray;
63
import org.json.JSONObject;
64
import org.springframework.beans.factory.annotation.Autowired;
65
import org.springframework.core.io.ByteArrayResource;
66
import org.springframework.http.HttpHeaders;
67
import org.springframework.http.HttpStatus;
68
import org.springframework.http.ResponseEntity;
69
import org.springframework.mail.javamail.JavaMailSender;
70
import org.springframework.stereotype.Controller;
71
import org.springframework.transaction.annotation.Transactional;
72
import org.springframework.ui.Model;
73
import org.springframework.web.bind.annotation.RequestBody;
74
import org.springframework.web.bind.annotation.RequestMapping;
75
import org.springframework.web.bind.annotation.RequestMethod;
76
import org.springframework.web.bind.annotation.RequestParam;
23796 amit.gupta 77
 
30017 amit.gupta 78
import javax.servlet.http.HttpServletRequest;
33812 tejus.loha 79
import java.math.BigDecimal;
30017 amit.gupta 80
import java.time.LocalDate;
81
import java.time.LocalDateTime;
82
import java.time.LocalTime;
33806 tejus.loha 83
import java.time.YearMonth;
30017 amit.gupta 84
import java.util.*;
85
import java.util.Map.Entry;
86
import java.util.function.Function;
87
import java.util.stream.Collectors;
88
 
23405 amit.gupta 89
@Controller
90
@Transactional(rollbackFor = Throwable.class)
91
public class IndentController {
92
 
32839 amit.gupta 93
    private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
94
    private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 95
 
32839 amit.gupta 96
    private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
97
            OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
98
            OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
99
            OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 100
 
32839 amit.gupta 101
    private static final int PLANNING_OPEN_DAY = 20;
102
    private static final int PLANNING_CLOSE_DAY = 1;
26951 amit.gupta 103
 
32839 amit.gupta 104
    private static final String PO_TITLE_STRING = "Alert - Stock Arriving at SD Warehouse";
30017 amit.gupta 105
 
32839 amit.gupta 106
    @Autowired
107
    WalletService walletService;
24231 amit.gupta 108
 
32839 amit.gupta 109
    @Autowired
110
    BrandRegionMappingRepository brandRegionMappingRepository;
30017 amit.gupta 111
 
32839 amit.gupta 112
    @Autowired
113
    private JavaMailSender googleMailSender;
25721 tejbeer 114
 
32839 amit.gupta 115
    @Autowired
35957 amit 116
    private MailOutboxService mailOutboxService;
117
 
118
    @Autowired
34490 ranu 119
    private ResponseSender responseSender;
120
 
121
    @Autowired
32839 amit.gupta 122
    private CookiesProcessor cookiesProcessor;
24231 amit.gupta 123
 
32839 amit.gupta 124
    @Autowired
125
    private UserWalletRepository userWalletRepository;
23785 amit.gupta 126
 
32839 amit.gupta 127
    @Autowired
128
    private UserRepository userRepository;
23796 amit.gupta 129
 
32839 amit.gupta 130
    @Autowired
131
    FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 132
 
32839 amit.gupta 133
    @Autowired
134
    private OrderRepository orderRepository;
23796 amit.gupta 135
 
32839 amit.gupta 136
    @Autowired
137
    private UserAccountRepository userAccountRepository;
26846 tejbeer 138
 
32839 amit.gupta 139
    @Autowired
140
    private ItemRepository itemRepository;
23405 amit.gupta 141
 
32839 amit.gupta 142
    @Autowired
143
    private StockAllocationService stockAllocationService;
23779 amit.gupta 144
 
32839 amit.gupta 145
    @Autowired
146
    private RetailerService retailerService;
23405 amit.gupta 147
 
32839 amit.gupta 148
    @Autowired
149
    private TagListingRepository tagListingRepository;
23405 amit.gupta 150
 
32839 amit.gupta 151
    @Autowired
35547 amit 152
    private TagListingEventPublisher tagListingEventPublisher;
153
 
154
    @Autowired
32839 amit.gupta 155
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
23405 amit.gupta 156
 
32839 amit.gupta 157
    @Autowired
35771 ranu 158
    private InventoryItemRepository inventoryItemRepository;
159
 
160
    @Autowired
32839 amit.gupta 161
    private PurchaseRepository purchaseRepository;
23796 amit.gupta 162
 
32839 amit.gupta 163
    @Autowired
164
    private MVCResponseSender mvcResponseSender;
23405 amit.gupta 165
 
32839 amit.gupta 166
    @Autowired
167
    private FocusedModelRepository focusedModelRepository;
25721 tejbeer 168
 
32839 amit.gupta 169
    @Autowired
170
    private MonthlyPlannedRepository monthlyPlannedRepository;
25721 tejbeer 171
 
32839 amit.gupta 172
    @Autowired
173
    private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 174
 
32839 amit.gupta 175
    @Autowired
176
    private FofoOrderItemRepository fofoOrderItemRepository;
25732 tejbeer 177
 
32839 amit.gupta 178
    @Autowired
179
    private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 180
 
32839 amit.gupta 181
    @Autowired
182
    RoleManager roleManager;
23405 amit.gupta 183
 
32839 amit.gupta 184
    @Autowired
185
    PartnerTypeChangeRepository partnerTypeChangeRepository;
27081 tejbeer 186
 
32839 amit.gupta 187
    @Autowired
188
    private Mongo mongoClient;
25736 tejbeer 189
 
32839 amit.gupta 190
    @Autowired
191
    private InventoryService inventoryService;
25736 tejbeer 192
 
32839 amit.gupta 193
    @Autowired
194
    private CsService1 csService1;
31663 amit.gupta 195
 
32839 amit.gupta 196
    @Autowired
197
    private CsService csService;
25721 tejbeer 198
 
32839 amit.gupta 199
    @Autowired
200
    private AuthRepository authRepository;
201
    @Autowired
202
    WarehouseRepository warehouseRepository;
203
    @Autowired
204
    private SuggestedPoRepository suggestedPoRepository;
26846 tejbeer 205
 
32839 amit.gupta 206
    @Autowired
207
    private NotificationService notificationService;
26846 tejbeer 208
 
32839 amit.gupta 209
    @Autowired
210
    private RegionRepository regionRepository;
27088 tejbeer 211
 
32839 amit.gupta 212
    @Autowired
213
    private PartnerRegionRepository partnerRegionRepository;
27088 tejbeer 214
 
32839 amit.gupta 215
    @Autowired
216
    private SaholicInventoryCISRepository saholicInventoryCISRepository;
27768 tejbeer 217
 
32839 amit.gupta 218
    @Autowired
219
    private SaholicInventoryService saholicInventoryService;
27768 tejbeer 220
 
32839 amit.gupta 221
    @Autowired
222
    private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
223
    @Autowired
224
    private SuggestedPoDetailRepository suggestedPoDetailRepository;
30003 tejbeer 225
 
32839 amit.gupta 226
    @Autowired
227
    SaholicCISTableRepository saholicCISTableRepository;
30664 amit.gupta 228
 
33812 tejus.loha 229
    @Autowired
230
    MonthlyTargetRepository monthlyTargetRepository;
231
 
232
    @Autowired
34035 ranu 233
    AgeingService ageingService;
234
 
235
    @Autowired
33812 tejus.loha 236
    LoanRepository loanRepository;
237
 
34397 ranu 238
    @Autowired
35811 amit 239
    SDCreditService sdCreditService;
240
 
241
    @Autowired
34397 ranu 242
    RbmTargetService rbmTargetService;
243
 
244
    @Autowired
245
    FofoUser fofoUser;
246
 
247
    @Autowired
34513 ranu 248
    BrandsService brandsService;
249
 
250
    @Autowired
34397 ranu 251
    SDCreditRequirementRepository sdCreditRequirementRepository;
252
 
35765 ranu 253
    @Autowired
254
    CategorisedCatalogRepository categorisedCatalogRepository;
255
 
32839 amit.gupta 256
    @RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
257
    public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
258
                                 @RequestParam int itemQty, @RequestParam int fofoId) throws Exception {
259
        if (fofoId == 0) {
27088 tejbeer 260
 
32839 amit.gupta 261
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
262
            fofoId = loginDetails.getFofoId();
27088 tejbeer 263
 
32839 amit.gupta 264
        }
27088 tejbeer 265
 
32839 amit.gupta 266
        LocalDate currentMonthDate = LocalDate.now();
267
        MonthlyPlanned monthlyPlanned = null;
25721 tejbeer 268
 
32839 amit.gupta 269
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
270
            currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
271
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
272
            LOGGER.info("monthlyPlanned" + monthlyPlanned);
273
            saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);
274
        }
275
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
276
        return "response";
277
    }
26082 tejbeer 278
 
32839 amit.gupta 279
    private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
280
                                    int catalogId, int itemQty) {
281
        if (monthlyPlanned == null) {
282
            monthlyPlanned = new MonthlyPlanned();
283
            monthlyPlanned.setFofoId(fofoId);
284
            monthlyPlanned.setYearMonth(currentMonthDate);
285
            monthlyPlannedRepository.persist(monthlyPlanned);
286
            PlannedDetail pd = new PlannedDetail();
287
            pd.setCatalogId(catalogId);
288
            pd.setPlannedId(monthlyPlanned.getId());
289
            pd.setQuantity(itemQty);
290
            pd.setUpdatedTimestamp(LocalDateTime.now());
291
            plannedDetailRepository.persist(pd);
25721 tejbeer 292
 
32839 amit.gupta 293
        } else {
294
            PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
295
                    catalogId);
296
            if (plannedDetail == null) {
297
                plannedDetail = new PlannedDetail();
298
                plannedDetail.setCatalogId(catalogId);
299
                plannedDetail.setPlannedId(monthlyPlanned.getId());
300
                plannedDetail.setQuantity(itemQty);
301
                plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
302
                plannedDetailRepository.persist(plannedDetail);
303
            } else if (itemQty == 0) {
304
                plannedDetailRepository.delete(plannedDetail);
25721 tejbeer 305
 
32839 amit.gupta 306
            } else {
307
                plannedDetail.setCatalogId(catalogId);
308
                plannedDetail.setQuantity(itemQty);
309
                plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
310
            }
25721 tejbeer 311
 
32839 amit.gupta 312
        }
25721 tejbeer 313
 
32839 amit.gupta 314
    }
25721 tejbeer 315
 
32839 amit.gupta 316
    @RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
317
    public String confirmOpenIndent(HttpServletRequest request,
318
                                    @RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {
26748 tejbeer 319
 
32839 amit.gupta 320
        if (fofoId == 0) {
321
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
322
            fofoId = loginDetails.getFofoId();
323
        }
324
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26748 tejbeer 325
 
32839 amit.gupta 326
        LocalDate currentDate = LocalDate.now();
327
        LocalDate planningMonthDate = null;
328
        MonthlyPlanned monthlyPlanned = null;
329
        if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {
330
            planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
331
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
25721 tejbeer 332
 
32839 amit.gupta 333
            confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
34952 ranu 334
        } else if (currentDate.isBefore(currentDate.withDayOfMonth(8))) {
335
            planningMonthDate = LocalDate.now().withDayOfMonth(1);
336
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
337
 
338
            confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
32839 amit.gupta 339
        }
340
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
26082 tejbeer 341
 
32839 amit.gupta 342
        return "response";
343
    }
26082 tejbeer 344
 
32839 amit.gupta 345
    private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
346
            throws Exception {
347
        List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
25721 tejbeer 348
 
32839 amit.gupta 349
        List<PlannedModel> plannedModel = new ArrayList<>();
350
        for (PlannedDetail plannedDetail : plannedDetails) {
25721 tejbeer 351
 
32839 amit.gupta 352
            List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
353
            String itemDesription = items.get(0).getItemDescriptionNoColor();
354
            PlannedModel pm = new PlannedModel();
355
            pm.setItemDescription(itemDesription);
356
            pm.setStoreName(customRetailer.getBusinessName());
357
            pm.setQty(plannedDetail.getQuantity());
358
            pm.setFofoId(fofoId);
359
            plannedModel.add(pm);
360
            LOGGER.info("plannedModel" + plannedModel);
25721 tejbeer 361
 
32839 amit.gupta 362
        }
363
        List<String> ccemails = new ArrayList<>();
364
        LOGGER.info("ccemails" + ccemails);
365
        Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);
366
        LOGGER.info("emailEsclationType" + emailEsclationType);
367
        if (emailEsclationType.get(EscalationType.L1) != null) {
368
            ccemails.add(emailEsclationType.get(EscalationType.L1));
369
        }
31636 tejbeer 370
 
32839 amit.gupta 371
        if (emailEsclationType.get(EscalationType.L2) != null) {
31636 tejbeer 372
 
32839 amit.gupta 373
            ccemails.add(emailEsclationType.get(EscalationType.L2));
374
        }
375
        LOGGER.info("ccemails" + ccemails);
376
        List<String> bccemails = new ArrayList<>();
377
        bccemails.add(emailEsclationType.get(EscalationType.L3));
378
        LOGGER.info("bccemails" + bccemails);
379
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
380
                Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
381
                plannedModel.stream()
382
                        .map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
383
                        .collect(Collectors.toList()));
384
        LOGGER.info("baos" + baos);
35957 amit 385
        mailOutboxService.queueMailWithAttachmentsViaGoogle(new String[]{customRetailer.getEmail()},
32839 amit.gupta 386
                ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),
35957 amit 387
                "Planned Indent", "PFA", false, "IndentController.confirmMonthlyPlanned",
388
                new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())));
25721 tejbeer 389
 
32839 amit.gupta 390
    }
23405 amit.gupta 391
 
32839 amit.gupta 392
    @RequestMapping(value = "/indent/download", method = RequestMethod.GET)
393
    public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
394
                                                            @RequestParam(required = false, defaultValue = "0") int fofoId,
395
                                                            @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
396
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
397
        Set<Integer> roleIds = loginDetails.getRoleIds();
398
        LOGGER.info("Counter size is {}", counterSize);
399
        LOGGER.info("Fofo Id is {}", fofoId);
30426 tejbeer 400
 
32839 amit.gupta 401
        if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
402
            List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
403
                    .collect(Collectors.toList());
404
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
405
            Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x))
406
                    .filter(x -> x != null).collect(Collectors.toList()).stream()
407
                    .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
408
            List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
409
                    true);
410
            Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
411
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 412
 
32839 amit.gupta 413
            Map<String, Integer> catalogUserQtyMap = new HashMap<>();
414
            currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
415
                int retailerId = x.getFofoId();
416
                int catalogId;
417
                try {
418
                    catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
419
                    String key = catalogId + "-" + retailerId;
420
                    if (!catalogUserQtyMap.containsKey(key)) {
421
                        catalogUserQtyMap.put(key, 0);
422
                    }
423
                    catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
424
                } catch (ProfitMandiBusinessException e) {
425
                    // TODO Auto-generated catch block
426
                    throw new RuntimeException(e);
427
                }
428
            });
23779 amit.gupta 429
 
32839 amit.gupta 430
            List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
431
            Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
432
                try {
433
                    return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
434
                            + x.getRetailerId();
435
                } catch (ProfitMandiBusinessException e) {
436
                    // TODO Auto-generated catch block
437
                    return "";
438
                }
439
            }, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 440
 
32839 amit.gupta 441
            Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
24232 amit.gupta 442
 
32839 amit.gupta 443
            List<TagListing> tagListings = tagListingRepository.selectAll(true);
444
            Iterator<TagListing> iterator = tagListings.iterator();
445
            while (iterator.hasNext()) {
446
                TagListing tagListing = iterator.next();
447
                Item item = itemRepository.selectById(tagListing.getItemId());
448
                int catalogId = item.getCatalogItemId();
449
                if (item.getCategoryId() != 10006) {
450
                    continue;
451
                }
23779 amit.gupta 452
 
32839 amit.gupta 453
                int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
454
                        ? modelStockAllocationMap.get(catalogId)
455
                        : 0;
456
                for (int retailerId : fofoIds) {
457
                    String key = catalogId + "-" + retailerId;
458
                    if (catalogListingMap.containsKey(key)) {
459
                        continue;
460
                    }
461
                    int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
462
                    int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
463
                    if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
464
                        continue;
465
                    }
466
                    CatalogListingModel catalogListingModel = new CatalogListingModel();
467
                    catalogListingModel.setFofoId(retailerId);
468
                    catalogListingModel.setModelName(item.getModelName());
469
                    catalogListingModel.setModelNumber(item.getModelNumber());
470
                    catalogListingModel.setCatalogId(catalogId);
471
                    catalogListingModel.setDp(tagListing.getSellingPrice());
472
                    catalogListingModel.setMop(tagListing.getMop());
473
                    catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
474
                    catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
475
                    catalogListingModel.setInTransitQuantity(catalogInTransit);
476
                    catalogListingModel
477
                            .setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
478
                    catalogListingModel.setStockInHand(catalogInStock);
479
                    catalogListingModel.setBrand(item.getBrand());
480
                    catalogListingModel.setModelName(item.getModelName());
481
                    catalogListingModel.setModelNumber(item.getModelNumber());
482
                    catalogListingModel.setCategoryId(item.getCategoryId());
483
                    catalogListingMap.put(key, catalogListingModel);
484
                }
485
            }
486
            List<List<?>> listOfRows = new ArrayList<>();
487
            for (CatalogListingModel clm : catalogListingMap.values()) {
488
                CustomRetailer cr = crm.get(clm.getFofoId());
489
                listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
490
                        clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
491
                        clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
492
                        clm.getToBeOrdered()));
493
            }
494
            ByteArrayOutputStream baos = FileUtil
495
                    .getCSVByteStream(
496
                            Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
497
                                    "DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
498
                            listOfRows);
499
            HttpHeaders headers = new HttpHeaders();
500
            headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
501
            headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
502
            return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
503
                    HttpStatus.OK);
504
        }
505
        return null;
24232 amit.gupta 506
 
32839 amit.gupta 507
    }
23405 amit.gupta 508
 
32839 amit.gupta 509
    @RequestMapping(value = "/itemsByCatalogId")
510
    public String getItemsByCatalogId(HttpServletRequest request, Model model,
511
                                      @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
512
            throws ProfitMandiBusinessException {
513
        if (catalogId == 0) {
514
            catalogId = itemRepository.selectById(itemId).getCatalogItemId();
515
        }
516
        List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
517
        LOGGER.info("Items {}", items);
518
        Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
519
                .collect(Collectors.toMap(Item::getId, Item::getColor));
520
        Map<Integer, TagListing> tagsMap = tagListingRepository
521
                .selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
522
                .stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
523
        LOGGER.info("Items color map {}", itemsColorMap);
524
        JSONArray response = new JSONArray();
525
        itemsColorMap.keySet().stream().forEach(x -> {
526
            response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
527
                    tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
528
        });
529
        model.addAttribute("response1", response.toString());
530
        return "response";
24410 amit.gupta 531
 
32839 amit.gupta 532
    }
24349 amit.gupta 533
 
32839 amit.gupta 534
    @RequestMapping(value = "/hotdealsitemsByCatalogId")
535
    public String getHotdealsitemsByCatalogId(HttpServletRequest request, Model model,
536
                                              @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
537
            throws ProfitMandiBusinessException {
538
        if (catalogId == 0) {
539
            catalogId = itemRepository.selectById(itemId).getCatalogItemId();
540
        }
541
        List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
542
        LOGGER.info("Items {}", items);
543
        Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
544
                .collect(Collectors.toMap(Item::getId, Item::getColor));
545
        Map<Integer, TagListing> tagsMap = tagListingRepository
546
                .selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
547
                .stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
548
        LOGGER.info("Items color map {}", itemsColorMap);
549
        JSONArray response = new JSONArray();
550
        itemsColorMap.keySet().stream().forEach(x -> {
551
            response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("hotDeals",
552
                    tagsMap.get(x) == null ? false : tagsMap.get(x).isHotDeals()));
553
        });
554
        model.addAttribute("response1", response.toString());
555
        return "response";
28055 tejbeer 556
 
32839 amit.gupta 557
    }
28055 tejbeer 558
 
32839 amit.gupta 559
    private List<Order> filterValidOrders(List<Order> lastOrdersList) {
560
        int orderRemovedCount = 0;
561
        Iterator<Order> orderIterator = lastOrdersList.iterator();
562
        while (orderIterator.hasNext()) {
563
            Order o = orderIterator.next();
564
            if (o.getInvoiceNumber() != null) {
565
                try {
566
                    purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
567
                    orderIterator.remove();
568
                    orderRemovedCount++;
569
                } catch (Exception e) {
30664 amit.gupta 570
 
32839 amit.gupta 571
                }
572
            }
573
        }
574
        LOGGER.info("Order removed count is {}", orderRemovedCount);
575
        return lastOrdersList;
576
    }
30664 amit.gupta 577
 
32839 amit.gupta 578
    // Clean up the saholic cis table
579
    @RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
580
    public String updateTagListing(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
581
            throws Exception {
582
        JSONArray jsonArray = new JSONArray(jsonArrayString);
35547 amit 583
        Set<Integer> updatedCatalogIds = new HashSet<>();
584
 
32839 amit.gupta 585
        for (int i = 0; i < jsonArray.length(); i++) {
586
            JSONObject obj = jsonArray.getJSONObject(i);
35547 amit 587
            int itemId = obj.getInt("id");
588
            TagListing tl = tagListingRepository.selectByItemId(itemId);
32839 amit.gupta 589
            if (tl == null) {
590
                continue;
591
            } else {
592
                tl.setActive(obj.getBoolean("active"));
593
                if (!tl.isActive()) {
594
                    saholicCISTableRepository.selectAllByItemId(tl.getItemId()).stream()
595
                            .forEach(x -> saholicCISTableRepository.delete(x));
596
                }
35547 amit 597
                // Collect catalogIds for Solr updates
598
                try {
599
                    Item item = itemRepository.selectById(itemId);
600
                    updatedCatalogIds.add(item.getCatalogItemId());
601
                } catch (Exception e) {
602
                    LOGGER.error("Failed to get catalogId for itemId: {}", itemId, e);
603
                }
32839 amit.gupta 604
            }
605
        }
35547 amit 606
 
607
        // Publish events for all updated catalogs
608
        for (Integer catalogId : updatedCatalogIds) {
609
            try {
610
                tagListingEventPublisher.publishStatusChange(0, catalogId);
611
            } catch (Exception e) {
612
                LOGGER.error("Failed to publish status change event for catalogId: {}", catalogId, e);
613
            }
614
        }
615
 
32839 amit.gupta 616
        model.addAttribute("response1", true);
617
        return "response";
618
    }
30664 amit.gupta 619
 
32839 amit.gupta 620
    @RequestMapping(value = "/indent/confirm-hotdeals-pause", method = RequestMethod.POST)
621
    public String hotdealUpdate(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
622
            throws Exception {
623
        JSONArray jsonArray = new JSONArray(jsonArrayString);
35547 amit 624
        Set<Integer> updatedCatalogIds = new HashSet<>();
625
 
32839 amit.gupta 626
        for (int i = 0; i < jsonArray.length(); i++) {
627
            JSONObject obj = jsonArray.getJSONObject(i);
35547 amit 628
            int itemId = obj.getInt("id");
629
            TagListing tl = tagListingRepository.selectByItemId(itemId);
32839 amit.gupta 630
            if (tl == null) {
631
                continue;
632
            } else {
633
                tl.setHotDeals(obj.getBoolean("hotDeals"));
634
                tagListingRepository.persist(tl);
35547 amit 635
                // Collect catalogIds for Solr updates
636
                try {
637
                    Item item = itemRepository.selectById(itemId);
638
                    updatedCatalogIds.add(item.getCatalogItemId());
639
                } catch (Exception e) {
640
                    LOGGER.error("Failed to get catalogId for itemId: {}", itemId, e);
641
                }
32839 amit.gupta 642
            }
643
        }
35547 amit 644
 
645
        // Publish events for all updated catalogs
646
        for (Integer catalogId : updatedCatalogIds) {
647
            try {
648
                tagListingEventPublisher.publishStatusChange(0, catalogId);
649
            } catch (Exception e) {
650
                LOGGER.error("Failed to publish status change event for catalogId: {}", catalogId, e);
651
            }
652
        }
653
 
32839 amit.gupta 654
        model.addAttribute("response1", true);
655
        return "response";
656
    }
30664 amit.gupta 657
 
32839 amit.gupta 658
    @RequestMapping(value = "/indent/loadIndent")
659
    public String loadOpenIndent(HttpServletRequest request, Model model,
660
                                 @RequestParam(required = false, defaultValue = "0") int fofoId,
661
                                 @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 662
 
32839 amit.gupta 663
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
664
        Set<Integer> roleIds = loginDetails.getRoleIds();
665
        LOGGER.info("Counter size is {}", counterSize);
666
        LOGGER.info("Fofo Id is {}", fofoId);
667
        boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 668
 
34952 ranu 669
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
25797 tejbeer 670
 
32839 amit.gupta 671
        Map<String, Object> equalsMap = new HashMap<>();
672
        equalsMap.put("categoryId", 10006);
673
        equalsMap.put("brand", brands);
674
        Map<String, List<?>> notEqualsMap = new HashMap<>();
25796 tejbeer 675
 
32839 amit.gupta 676
        Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
677
        Map<Integer, Integer> currentStockMap;
25796 tejbeer 678
 
32839 amit.gupta 679
        if (!isAdmin && fofoId == 0) {
680
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
681
            Map<String, Object> equalsStockJoinMap = new HashMap<>();
682
            equalsStockJoinMap.put("fofoId", fofoId);
683
            currentStockMap = itemRepository
684
                    .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
685
                            equalsStockJoinMap, notEqualsJoinMap, "availability")
686
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
687
            LOGGER.info("currentStock");
688
        } else {
689
            if (fofoId == 0) {
25796 tejbeer 690
 
32839 amit.gupta 691
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
692
                equalsStockJoinMap.put("fofoId", fofoId);
25796 tejbeer 693
 
32839 amit.gupta 694
                currentStockMap = itemRepository
695
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
696
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
697
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25796 tejbeer 698
 
32839 amit.gupta 699
            } else {
25796 tejbeer 700
 
32839 amit.gupta 701
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
702
                equalsStockJoinMap.put("fofoId", fofoId);
25796 tejbeer 703
 
32839 amit.gupta 704
                currentStockMap = itemRepository
705
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
706
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
707
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25796 tejbeer 708
 
32839 amit.gupta 709
            }
710
        }
25796 tejbeer 711
 
32839 amit.gupta 712
        LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 713
 
32839 amit.gupta 714
        Map<Integer, Integer> itemsInTransit = null;
715
        List<TagListing> tagListings = tagListingRepository.selectAll(true);
716
        if (!isAdmin) {
717
            tagListings = new ArrayList<>(tagListings);
718
            List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
719
                    OrderRepository.validOrderStatusList);
720
            inTransitOrders = this.filterValidOrders(inTransitOrders);
721
            itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
722
                    Collectors.summingInt(x -> x.getLineItem().getQuantity())));
723
        } else {
724
            itemsInTransit = new HashMap<>();
725
        }
25797 tejbeer 726
 
32839 amit.gupta 727
        int totalPcs = 0;
25797 tejbeer 728
 
32839 amit.gupta 729
        float totalAmount = 0;
730
        Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
731
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
732
                .collect(Collectors.toList());
25796 tejbeer 733
 
32839 amit.gupta 734
        LOGGER.info("regionIds" + regionIds);
735
        Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
736
                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
737
        LOGGER.info("focusedModelMap" + focusedModelMap);
738
        LocalDate planningMonthDate = null;
739
        MonthlyPlanned monthlyPlanned = null;
740
        List<Integer> fofoOrderIds = null;
741
        LOGGER.info("localDate" + LocalDate.now());
742
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
743
            planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
744
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
745
            LOGGER.info("monthlyPlanned2" + monthlyPlanned);
746
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
747
                            LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
748
                    .collect(Collectors.toList());
749
            model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
34952 ranu 750
        } else if (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(8))) {
751
            planningMonthDate = LocalDate.now().withDayOfMonth(8);
752
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
753
            LOGGER.info("monthlyPlanned2" + monthlyPlanned);
754
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
755
                            LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
756
                    .collect(Collectors.toList());
757
            model.addAttribute("planningMonth", LocalDate.now().getMonth());
32839 amit.gupta 758
        } else {
759
            planningMonthDate = LocalDate.now().withDayOfMonth(1);
760
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
761
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
762
            model.addAttribute("planningMonth", planningMonthDate.getMonth());
763
            model.addAttribute("mtd", true);
764
            model.addAttribute("freezed", true);
765
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
766
                            curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
767
                    .collect(Collectors.toList());
768
            LOGGER.info("monthlyPlanned1" + monthlyPlanned);
769
        }
26082 tejbeer 770
 
32839 amit.gupta 771
        Map<Integer, Integer> plannedDetailMap = null;
772
        if (monthlyPlanned != null) {
773
            plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
774
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
25721 tejbeer 775
 
32839 amit.gupta 776
        }
777
        LOGGER.info("plannedDetailMap" + plannedDetailMap);
26176 tejbeer 778
 
32839 amit.gupta 779
        LOGGER.info("fofoOrderIds" + fofoOrderIds);
780
        Map<String, Object> equalsJoinMap = new HashMap<>();
26618 tejbeer 781
 
32839 amit.gupta 782
        equalsJoinMap.put("orderId", fofoOrderIds);
783
        Map<Integer, Integer> last15daysMap = null;
784
        if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
24231 amit.gupta 785
 
32839 amit.gupta 786
            last15daysMap = itemRepository
787
                    .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
788
                            notEqualsJoinMap, "quantity")
789
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
790
        }
791
        LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 792
 
32839 amit.gupta 793
        Map<Integer, TagListing> taglistingMap = tagListings.stream()
794
                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
795
        List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
796
        Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
797
                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
798
        LOGGER.info("catalogIdItemMap");
24231 amit.gupta 799
 
32839 amit.gupta 800
        Map<String, Object> equalsItemJoinMap = new HashMap<>();
801
        equalsItemJoinMap.put("active", 1);
802
        List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
803
                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
804
        LOGGER.info("tagListingCatalogIds");
805
        for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
806
            int catalogId = catalogIdAggregateValue.getCatalogId();
807
            Item item = catalogIdItemMap.get(catalogId).get(0);
808
            TagListing tagListing = taglistingMap.get(item.getId());
809
            CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
810
            if (!catalogListingMap.containsKey(catalogId)) {
811
                catalogListingModel = new CatalogListingModel();
812
                catalogListingModel.setCatalogId(catalogId);
813
                catalogListingModel.setDp(tagListing.getSellingPrice());
814
                catalogListingModel.setMop(tagListing.getMop());
815
                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
816
                if (plannedDetailMap != null) {
25721 tejbeer 817
 
32839 amit.gupta 818
                    Integer quantity = plannedDetailMap.get(catalogId);
819
                    if (quantity != null) {
820
                        catalogListingModel.setAllocatedQuantity(quantity);
821
                    }
822
                }
25721 tejbeer 823
 
32839 amit.gupta 824
                if (last15daysMap != null) {
825
                    Integer last15DaysSale = last15daysMap.get(catalogId);
25796 tejbeer 826
 
32839 amit.gupta 827
                    if (last15DaysSale != null) {
828
                        catalogListingModel.setLast15DaysSale(last15DaysSale);
829
                    } else {
830
                        catalogListingModel.setLast15DaysSale(0);
831
                    }
832
                } else {
833
                    catalogListingModel.setLast15DaysSale(0);
834
                }
25721 tejbeer 835
 
32839 amit.gupta 836
                catalogListingModel.setBrand(item.getBrand());
837
                if (item.getCategoryId() == 10006) {
838
                    catalogListingModel.setCategoryId(item.getCategoryId());
839
                }
25721 tejbeer 840
 
32839 amit.gupta 841
                FocusedModel fm = focusedModelMap.get(catalogId);
842
                if (fm != null) {
843
                    catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
844
                    catalogListingModel.setMinimumQty(fm.getMinimumQty());
25721 tejbeer 845
 
32839 amit.gupta 846
                } else {
847
                    catalogListingModel.setRecommendedQty(0);
848
                    catalogListingModel.setMinimumQty(0);
849
                }
25721 tejbeer 850
 
32839 amit.gupta 851
                catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 852
 
32839 amit.gupta 853
            }
854
            int itemAvailability = 0;
855
            if (currentStockMap != null) {
856
                Integer qty = currentStockMap.get(catalogId);
857
                itemAvailability = qty == null ? 0 : qty;
858
                catalogListingModel.setStockInHand(itemAvailability);
859
            } else {
860
                catalogListingModel.setStockInHand(0);
861
            }
862
            Integer inTransitQuantity = itemsInTransit.get(item.getId());
863
            int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
864
            catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
865
            if (plannedDetailMap != null) {
866
                if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 867
 
32839 amit.gupta 868
                    int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
869
                            + catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
870
                    LOGGER.info("remaning" + remaining);
26176 tejbeer 871
 
32839 amit.gupta 872
                    if (remaining != 0) {
873
                        catalogListingModel.setRemaining(remaining);
874
                    } else {
875
                        catalogListingModel.setRemaining(0);
876
                    }
877
                }
878
            }
879
        }
25721 tejbeer 880
 
32839 amit.gupta 881
        Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
882
        if (fofoId > 0) {
883
            CustomRetailer customRetailer = customRetailersMap.get(fofoId);
884
            model.addAttribute("retailerName",
885
                    customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
886
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
887
            model.addAttribute("retailerId", customRetailer.getPartnerId());
888
            model.addAttribute("counterSize", fs.getCounterSize().toString());
889
        } else {
890
            model.addAttribute("counterSize", counterSize.toString());
891
        }
892
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 893
 
32839 amit.gupta 894
        List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
25702 amit.gupta 895
 
32839 amit.gupta 896
        Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
897
                Comparator.reverseOrder());
898
        LOGGER.info("monthlyPlanned" + monthlyPlanned);
899
        model.addAttribute("catalogTagListings",
900
                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
901
        model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
902
        model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
903
        model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
904
        model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());
26131 tejbeer 905
 
32839 amit.gupta 906
        model.addAttribute("customRetailers", customRetailers);
907
        model.addAttribute("totalAmount", totalAmount);
908
        model.addAttribute("monthlyPlanned", monthlyPlanned);
909
        model.addAttribute("totalPcs", totalPcs);
910
        return "open-indent";
25796 tejbeer 911
 
32839 amit.gupta 912
    }
23796 amit.gupta 913
 
32839 amit.gupta 914
    @RequestMapping(value = "/indent/loadIndentPreviousMonth")
915
    public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
916
                                              @RequestParam(required = false, defaultValue = "0") int fofoId,
917
                                              @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
918
        LocalDate planMonthStart = null;
919
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
920
            planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
921
        } else {
922
            planMonthStart = LocalDate.now().withDayOfMonth(1);
923
        }
924
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
925
        Set<Integer> roleIds = loginDetails.getRoleIds();
926
        LOGGER.info("Counter size is {}", counterSize);
927
        LOGGER.info("Fofo Id is {}", fofoId);
928
        boolean isAdmin = roleManager.isAdmin(roleIds);
26131 tejbeer 929
 
34952 ranu 930
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
26131 tejbeer 931
 
32839 amit.gupta 932
        Map<String, Object> equalsMap = new HashMap<>();
933
        equalsMap.put("categoryId", 10006);
934
        equalsMap.put("brand", brands);
935
        Map<String, List<?>> notEqualsMap = new HashMap<>();
26131 tejbeer 936
 
32839 amit.gupta 937
        Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
938
        Map<Integer, Integer> currentStockMap;
26131 tejbeer 939
 
32839 amit.gupta 940
        if (!isAdmin && fofoId == 0) {
941
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
942
            Map<String, Object> equalsStockJoinMap = new HashMap<>();
943
            equalsStockJoinMap.put("fofoId", fofoId);
944
            currentStockMap = itemRepository
945
                    .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
946
                            equalsStockJoinMap, notEqualsJoinMap, "availability")
947
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
948
            LOGGER.info("currentStock");
949
        } else {
950
            if (fofoId == 0) {
26131 tejbeer 951
 
32839 amit.gupta 952
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
953
                equalsStockJoinMap.put("fofoId", fofoId);
26131 tejbeer 954
 
32839 amit.gupta 955
                currentStockMap = itemRepository
956
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
957
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
958
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26131 tejbeer 959
 
32839 amit.gupta 960
            } else {
26131 tejbeer 961
 
32839 amit.gupta 962
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
963
                equalsStockJoinMap.put("fofoId", fofoId);
26131 tejbeer 964
 
32839 amit.gupta 965
                currentStockMap = itemRepository
966
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
967
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
968
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26131 tejbeer 969
 
32839 amit.gupta 970
            }
971
        }
26131 tejbeer 972
 
32839 amit.gupta 973
        LOGGER.info("currentStock" + currentStockMap);
26131 tejbeer 974
 
32839 amit.gupta 975
        Map<Integer, Integer> itemsInTransit = null;
976
        List<TagListing> tagListings = tagListingRepository.selectAll(true);
977
        if (!isAdmin) {
978
            tagListings = new ArrayList<>(tagListings);
979
            List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
980
                    OrderRepository.validOrderStatusList);
981
            inTransitOrders = this.filterValidOrders(inTransitOrders);
982
            itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
983
                    Collectors.summingInt(x -> x.getLineItem().getQuantity())));
984
        } else {
985
            itemsInTransit = new HashMap<>();
986
        }
26131 tejbeer 987
 
32839 amit.gupta 988
        int totalPcs = 0;
26131 tejbeer 989
 
32839 amit.gupta 990
        float totalAmount = 0;
991
        Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
26131 tejbeer 992
 
32839 amit.gupta 993
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
994
                .collect(Collectors.toList());
26131 tejbeer 995
 
32839 amit.gupta 996
        Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
997
                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
27088 tejbeer 998
 
32839 amit.gupta 999
        MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
1000
                planMonthStart.minusMonths(1));
1001
        model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
1002
        model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
1003
        model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 1004
 
32839 amit.gupta 1005
        Map<Integer, Integer> plannedDetailMap = null;
1006
        if (monthlyPlanned != null) {
1007
            plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1008
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
26131 tejbeer 1009
 
32839 amit.gupta 1010
        }
26131 tejbeer 1011
 
32839 amit.gupta 1012
        LOGGER.info("plannedDetailMap" + plannedDetailMap);
1013
        List<Integer> fofoOrderIds = fofoOrderRepository
1014
                .selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1015
                        planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
1016
                .stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 1017
 
32839 amit.gupta 1018
        LOGGER.info("fofoOrderIds" + fofoOrderIds);
1019
        Map<String, Object> equalsJoinMap = new HashMap<>();
1020
        equalsJoinMap.put("orderId", fofoOrderIds);
1021
        Map<Integer, Integer> lastMonthSaleMap = null;
1022
        if (!fofoOrderIds.isEmpty()) {
1023
            lastMonthSaleMap = itemRepository
1024
                    .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1025
                            notEqualsJoinMap, "quantity")
1026
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1027
        }
1028
        LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
26131 tejbeer 1029
 
32839 amit.gupta 1030
        Map<Integer, TagListing> taglistingMap = tagListings.stream()
1031
                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1032
        List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1033
        Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1034
                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1035
        LOGGER.info("catalogIdItemMap");
26131 tejbeer 1036
 
32839 amit.gupta 1037
        Map<String, Object> equalsItemJoinMap = new HashMap<>();
1038
        equalsItemJoinMap.put("active", 1);
1039
        List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
1040
                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
1041
        LOGGER.info("tagListingCatalogIds");
1042
        for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
1043
            int catalogId = catalogIdAggregateValue.getCatalogId();
1044
            Item item = catalogIdItemMap.get(catalogId).get(0);
1045
            TagListing tagListing = taglistingMap.get(item.getId());
1046
            CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1047
            if (!catalogListingMap.containsKey(catalogId)) {
1048
                catalogListingModel = new CatalogListingModel();
1049
                catalogListingModel.setCatalogId(catalogId);
1050
                catalogListingModel.setDp(tagListing.getSellingPrice());
1051
                catalogListingModel.setMop(tagListing.getMop());
1052
                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1053
                if (plannedDetailMap != null) {
26131 tejbeer 1054
 
32839 amit.gupta 1055
                    Integer quantity = plannedDetailMap.get(catalogId);
1056
                    if (quantity != null) {
1057
                        catalogListingModel.setAllocatedQuantity(quantity);
1058
                    }
1059
                }
26131 tejbeer 1060
 
32839 amit.gupta 1061
                if (lastMonthSaleMap != null) {
1062
                    Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
26131 tejbeer 1063
 
32839 amit.gupta 1064
                    if (lastMonthSale != null) {
1065
                        catalogListingModel.setLastMonthSaleMap(lastMonthSale);
1066
                    } else {
1067
                        catalogListingModel.setLastMonthSaleMap(0);
1068
                    }
1069
                } else {
1070
                    catalogListingModel.setLast15DaysSale(0);
1071
                }
26131 tejbeer 1072
 
32839 amit.gupta 1073
                catalogListingModel.setBrand(item.getBrand());
1074
                if (item.getCategoryId() == 10006) {
1075
                    catalogListingModel.setCategoryId(item.getCategoryId());
1076
                }
26131 tejbeer 1077
 
32839 amit.gupta 1078
                FocusedModel fm = focusedModelMap.get(catalogId);
1079
                if (fm != null) {
1080
                    catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1081
                    catalogListingModel.setMinimumQty(fm.getMinimumQty());
26131 tejbeer 1082
 
32839 amit.gupta 1083
                } else {
1084
                    catalogListingModel.setRecommendedQty(0);
1085
                    catalogListingModel.setMinimumQty(0);
1086
                }
26131 tejbeer 1087
 
32839 amit.gupta 1088
                catalogListingMap.put(catalogId, catalogListingModel);
26131 tejbeer 1089
 
32839 amit.gupta 1090
            }
1091
            int itemAvailability = 0;
1092
            if (currentStockMap != null) {
1093
                Integer qty = currentStockMap.get(catalogId);
1094
                itemAvailability = qty == null ? 0 : qty;
1095
                catalogListingModel.setStockInHand(itemAvailability);
1096
            } else {
1097
                catalogListingModel.setStockInHand(0);
1098
            }
1099
            Integer inTransitQuantity = itemsInTransit.get(item.getId());
1100
            int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1101
            catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26131 tejbeer 1102
 
32839 amit.gupta 1103
        }
26131 tejbeer 1104
 
32839 amit.gupta 1105
        Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
1106
        if (fofoId > 0) {
1107
            CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1108
            model.addAttribute("retailerName",
1109
                    customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1110
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1111
            model.addAttribute("retailerId", customRetailer.getPartnerId());
1112
            model.addAttribute("counterSize", fs.getCounterSize().toString());
1113
        } else {
1114
            model.addAttribute("counterSize", counterSize.toString());
1115
        }
1116
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
26131 tejbeer 1117
 
32839 amit.gupta 1118
        List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
26131 tejbeer 1119
 
32839 amit.gupta 1120
        Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1121
                Comparator.reverseOrder());
1122
        LOGGER.info("monthlyPlanned" + monthlyPlanned);
1123
        model.addAttribute("catalogTagListings",
1124
                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1125
        model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1126
        model.addAttribute("previousMonth", true);
1127
        model.addAttribute("freezed", true);
1128
        model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
1129
        model.addAttribute("customRetailers", customRetailers);
1130
        model.addAttribute("totalAmount", totalAmount);
1131
        model.addAttribute("monthlyPlanned", monthlyPlanned);
1132
        model.addAttribute("totalPcs", totalPcs);
1133
        return "open-indent";
26131 tejbeer 1134
 
32839 amit.gupta 1135
    }
26131 tejbeer 1136
 
32839 amit.gupta 1137
    private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1138
        Map<Integer, Item> itemMap = new HashMap<>();
1139
        for (FocusedModel focusedModel : focusedModels) {
1140
            List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1141
            itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
1142
        }
23796 amit.gupta 1143
 
32839 amit.gupta 1144
        return itemMap;
1145
    }
25378 tejbeer 1146
 
32839 amit.gupta 1147
    private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
1148
        Map<Integer, Region> regionMap = new HashMap<>();
1149
        for (FocusedModel focusedModel : focusedModels) {
1150
            Region region = regionRepository.selectById(focusedModel.getRegionId());
1151
            regionMap.put(region.getId(), region);
1152
        }
24231 amit.gupta 1153
 
32839 amit.gupta 1154
        return regionMap;
1155
    }
24231 amit.gupta 1156
 
32839 amit.gupta 1157
    @RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1158
    public String getFocusedModel(HttpServletRequest request,
1159
                                  @RequestParam(name = "offset", defaultValue = "0") int offset,
33412 ranu 1160
                                  @RequestParam(name = "limit", defaultValue = "0") int limit, Model model)
32839 amit.gupta 1161
            throws ProfitMandiBusinessException {
25736 tejbeer 1162
 
32839 amit.gupta 1163
        long size = 0;
1164
        List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
33412 ranu 1165
        Collections.reverse(focusedModels);
32839 amit.gupta 1166
        size = focusedModelRepository.selectAllCount();
1167
        if (!focusedModels.isEmpty()) {
1168
            Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
1169
            Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25721 tejbeer 1170
 
32839 amit.gupta 1171
            LOGGER.info("regionMap" + regionMap);
1172
            model.addAttribute("focusedModels", focusedModels);
1173
            model.addAttribute("itemMap", itemMap);
1174
            model.addAttribute("regionMap", regionMap);
1175
            model.addAttribute("start", offset + 1);
1176
            model.addAttribute("size", size);
1177
            model.addAttribute("url", "/getPaginatedFocusedModel");
25736 tejbeer 1178
 
32839 amit.gupta 1179
            if (focusedModels.size() < limit) {
1180
                model.addAttribute("end", offset + focusedModels.size());
1181
            } else {
1182
                model.addAttribute("end", offset + limit);
1183
            }
1184
        } else {
32170 jai.hind 1185
 
32839 amit.gupta 1186
            model.addAttribute("walletRequest", focusedModels);
1187
            model.addAttribute("size", size);
32171 jai.hind 1188
 
32839 amit.gupta 1189
        }
25736 tejbeer 1190
 
32839 amit.gupta 1191
        List<Region> regions = regionRepository.selectAll();
27081 tejbeer 1192
 
32839 amit.gupta 1193
        model.addAttribute("regions", regions);
27088 tejbeer 1194
 
32839 amit.gupta 1195
        return "focused_model";
1196
    }
25721 tejbeer 1197
 
32839 amit.gupta 1198
    @RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1199
    public String getPaginatedFocusedModel(HttpServletRequest request,
1200
                                           @RequestParam(name = "offset", defaultValue = "0") int offset,
1201
                                           @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1202
            throws ProfitMandiBusinessException {
1203
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1204
        List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
25736 tejbeer 1205
 
32839 amit.gupta 1206
        if (!focusedModels.isEmpty()) {
1207
            Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
1208
            Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
1209
            model.addAttribute("focusedModels", focusedModels);
1210
            model.addAttribute("itemMap", itemMap);
1211
            model.addAttribute("regionMap", regionMap);
1212
            model.addAttribute("url", "/getPaginatedFocusedModel");
1213
        } else {
1214
            model.addAttribute("focusedModels", focusedModels);
25736 tejbeer 1215
 
32839 amit.gupta 1216
        }
27081 tejbeer 1217
 
32839 amit.gupta 1218
        List<Region> regions = regionRepository.selectAll();
27088 tejbeer 1219
 
32839 amit.gupta 1220
        model.addAttribute("regions", regions);
1221
        return "focused-model-paginated";
1222
    }
25736 tejbeer 1223
 
32839 amit.gupta 1224
    private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1225
        Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1226
 
35236 amit 1227
        List<BrandCatalog> mobileBrands = brandsService.getBrands(fofoId, null, 3);
32839 amit.gupta 1228
        List<BrandStockPrice> brandStockPrices = new ArrayList<>();
25798 tejbeer 1229
 
32839 amit.gupta 1230
        mobileBrands.stream().forEach(x -> {
35236 amit 1231
            String brand = x.getName();
32839 amit.gupta 1232
            if (brandStockPricesMap.containsKey(brand)) {
1233
                BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
35236 amit 1234
                brandStockPrice.setBrandUrl(x.getLogoUrl());
1235
                brandStockPrice.setRank(x.getBrandCategory().getRank());
32839 amit.gupta 1236
                brandStockPrices.add(brandStockPrice);
1237
            }
1238
        });
25798 tejbeer 1239
 
32839 amit.gupta 1240
        return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1241
                .collect(Collectors.toList());
1242
    }
25798 tejbeer 1243
 
32839 amit.gupta 1244
    @RequestMapping(value = "/getPartnerAllocation")
1245
    public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
26721 tejbeer 1246
 
32839 amit.gupta 1247
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1248
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
26721 tejbeer 1249
 
32839 amit.gupta 1250
        Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26721 tejbeer 1251
 
32839 amit.gupta 1252
        List<Integer> fofoIds = pp.get(authUser.getId());
26721 tejbeer 1253
 
32839 amit.gupta 1254
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1255
        Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1256
                .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1257
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1258
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
26721 tejbeer 1259
 
32839 amit.gupta 1260
        model.addAttribute("customRetailersMap", crm);
1261
        model.addAttribute("fofoStoreMap", fofoStoreMap);
1262
        return "partners_allocation";
26721 tejbeer 1263
 
32839 amit.gupta 1264
    }
26721 tejbeer 1265
 
32839 amit.gupta 1266
    @RequestMapping(value = "/partnerPendingOrder")
1267
    public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1268
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1269
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
26846 tejbeer 1270
 
32839 amit.gupta 1271
        Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26846 tejbeer 1272
 
32839 amit.gupta 1273
        List<Integer> fofoIds = pp.get(authUser.getId());
1274
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1275
        Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1276
                .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
26846 tejbeer 1277
 
32839 amit.gupta 1278
        model.addAttribute("customRetailersMap", crm);
26846 tejbeer 1279
 
32839 amit.gupta 1280
        return "partner-po";
26846 tejbeer 1281
 
32839 amit.gupta 1282
    }
26846 tejbeer 1283
 
32839 amit.gupta 1284
    @RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1285
    public String focusedModel(HttpServletRequest request, @RequestParam int catalogId,
1286
                               @RequestParam(name = "recommended", defaultValue = "0") int recommended,
1287
                               @RequestParam(name = "minimumQty", defaultValue = "0") int minimumQty,
1288
                               @RequestParam(name = "obvrecommend", defaultValue = "0") int obvrecommend,
1289
                               @RequestParam(name = "obvminimum", defaultValue = "0") int obvminimum, @RequestParam int regionId,
1290
                               Model model) throws ProfitMandiBusinessException {
30664 amit.gupta 1291
 
32839 amit.gupta 1292
        FocusedModel fm = new FocusedModel();
1293
        fm.setCatalogId(catalogId);
1294
        fm.setMinimumQty(minimumQty);
1295
        fm.setRecommendedQty(recommended);
1296
        fm.setRegionId(regionId);
1297
        fm.setObsRecommendedQty(obvrecommend);
1298
        fm.setObsMinimumQty(obvminimum);
1299
        fm.setCreatedTimestamp(LocalDateTime.now());
1300
        focusedModelRepository.persist(fm);
1301
        return "focused_model";
1302
    }
30664 amit.gupta 1303
 
32839 amit.gupta 1304
    @RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1305
    public String removeFocusedModelItem(HttpServletRequest request,
1306
                                         @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
30017 amit.gupta 1307
 
32839 amit.gupta 1308
        focusedModelRepository.deleteById(id);
1309
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1310
        return "response";
1311
    }
30017 amit.gupta 1312
 
32839 amit.gupta 1313
    @RequestMapping(value = "/getPartnerloadContent")
1314
    public String getPartnerloadContent(HttpServletRequest request, Model model,
1315
                                        @RequestParam(required = false, defaultValue = "0") int fofoId,
1316
                                        @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26846 tejbeer 1317
 
32839 amit.gupta 1318
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1319
        Set<Integer> roleIds = loginDetails.getRoleIds();
1320
        LOGGER.info("Counter size is {}", counterSize);
1321
        LOGGER.info("Fofo Id is {}", fofoId);
1322
        boolean isAdmin = roleManager.isAdmin(roleIds);
26846 tejbeer 1323
 
34952 ranu 1324
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
26846 tejbeer 1325
 
32839 amit.gupta 1326
        Map<String, Object> equalsMap = new HashMap<>();
1327
        equalsMap.put("categoryId", 10006);
1328
        equalsMap.put("brand", brands);
1329
        Map<String, List<?>> notEqualsMap = new HashMap<>();
26846 tejbeer 1330
 
32839 amit.gupta 1331
        Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1332
        Map<Integer, Integer> currentStockMap;
26846 tejbeer 1333
 
32839 amit.gupta 1334
        if (!isAdmin && fofoId == 0) {
1335
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1336
            Map<String, Object> equalsStockJoinMap = new HashMap<>();
1337
            equalsStockJoinMap.put("fofoId", fofoId);
1338
            currentStockMap = itemRepository
1339
                    .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1340
                            equalsStockJoinMap, notEqualsJoinMap, "availability")
1341
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1342
            LOGGER.info("currentStock");
1343
        } else {
1344
            if (fofoId == 0) {
26846 tejbeer 1345
 
32839 amit.gupta 1346
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
1347
                equalsStockJoinMap.put("fofoId", fofoId);
26846 tejbeer 1348
 
32839 amit.gupta 1349
                currentStockMap = itemRepository
1350
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1351
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
1352
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26846 tejbeer 1353
 
32839 amit.gupta 1354
            } else {
26846 tejbeer 1355
 
32839 amit.gupta 1356
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
1357
                equalsStockJoinMap.put("fofoId", fofoId);
26846 tejbeer 1358
 
32839 amit.gupta 1359
                currentStockMap = itemRepository
1360
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1361
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
1362
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26846 tejbeer 1363
 
32839 amit.gupta 1364
            }
1365
        }
26846 tejbeer 1366
 
32839 amit.gupta 1367
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
1368
        LOGGER.info("currentStock" + currentStockMap);
26846 tejbeer 1369
 
32839 amit.gupta 1370
        Map<Integer, Integer> itemsInTransit = null;
1371
        List<TagListing> tagListings = tagListingRepository.selectAll(true);
1372
        if (!isAdmin) {
1373
            tagListings = new ArrayList<>(tagListings);
1374
            List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
1375
                    OrderRepository.validOrderStatusList);
1376
            inTransitOrders = this.filterValidOrders(inTransitOrders);
1377
            itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1378
                    Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1379
        } else {
1380
            itemsInTransit = new HashMap<>();
1381
        }
26846 tejbeer 1382
 
32839 amit.gupta 1383
        int totalPcs = 0;
26846 tejbeer 1384
 
32839 amit.gupta 1385
        float totalAmount = 0;
1386
        Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
26846 tejbeer 1387
 
32839 amit.gupta 1388
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1389
                .collect(Collectors.toList());
26846 tejbeer 1390
 
32839 amit.gupta 1391
        Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1392
                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
27088 tejbeer 1393
 
32839 amit.gupta 1394
        LocalDate currentMonthDate = LocalDate.now();
1395
        MonthlyPlanned monthlyPlanned = null;
1396
        List<Integer> fofoOrderIds = null;
1397
        LOGGER.info("localDate" + LocalDate.now());
1398
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
1399
            currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1400
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1401
            LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1402
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1403
                            LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
1404
                    .collect(Collectors.toList());
26846 tejbeer 1405
 
32839 amit.gupta 1406
            model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
1407
        } else {
1408
            currentMonthDate = LocalDate.now().withDayOfMonth(1);
1409
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
1410
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1411
            model.addAttribute("planningMonth", currentMonthDate.getMonth());
1412
            model.addAttribute("mtd", true);
1413
            model.addAttribute("freezed", true);
1414
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1415
                            curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
1416
                    .collect(Collectors.toList());
1417
            LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1418
        }
26846 tejbeer 1419
 
32839 amit.gupta 1420
        Map<Integer, Integer> plannedDetailMap = null;
1421
        if (monthlyPlanned != null) {
1422
            plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1423
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
26846 tejbeer 1424
 
32839 amit.gupta 1425
        }
1426
        LOGGER.info("plannedDetailMap" + plannedDetailMap);
26846 tejbeer 1427
 
32839 amit.gupta 1428
        LOGGER.info("fofoOrderIds" + fofoOrderIds);
1429
        Map<String, Object> equalsJoinMap = new HashMap<>();
26846 tejbeer 1430
 
32839 amit.gupta 1431
        equalsJoinMap.put("orderId", fofoOrderIds);
1432
        Map<Integer, Integer> last15daysMap = null;
1433
        if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
26846 tejbeer 1434
 
32839 amit.gupta 1435
            last15daysMap = itemRepository
1436
                    .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1437
                            notEqualsJoinMap, "quantity")
1438
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1439
        }
1440
        LOGGER.info("last15daysMap" + last15daysMap);
26846 tejbeer 1441
 
32839 amit.gupta 1442
        Map<Integer, TagListing> taglistingMap = tagListings.stream()
1443
                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1444
        List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1445
        Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1446
                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1447
        LOGGER.info("catalogIdItemMap");
26846 tejbeer 1448
 
32839 amit.gupta 1449
        Map<String, Object> equalsItemJoinMap = new HashMap<>();
1450
        equalsItemJoinMap.put("active", 1);
1451
        List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
1452
                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
1453
        Map<Integer, Integer> ourStockAvailability = new HashMap<>();
27768 tejbeer 1454
 
32839 amit.gupta 1455
        Map<Integer, List<Integer>> catalogItemIdMap = itemRepository
1456
                .selectAllByCatalogIds(new HashSet<>(
1457
                        tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList())))
1458
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1459
                        Collectors.mapping(y -> y.getId(), Collectors.toList())));
1460
        for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {
1461
            List<Integer> itemIds = catalogItem.getValue();
1462
            int availability = 0;
1463
            for (Integer itemId : itemIds) {
1464
                List<SaholicCISTable> saholicCISTableList = saholicCISTableRepository.selectByItemWarehouse(itemId,
1465
                        fofoStore.getWarehouseId());
1466
                if (saholicCISTableList != null) {
1467
                    availability += saholicCISTableList.stream()
1468
                            .collect(Collectors.summingInt(x -> x.getAvailability()));
1469
                }
1470
            }
1471
            Integer catalogItemId = catalogItem.getKey();
1472
            ourStockAvailability.put(catalogItemId, availability);
1473
        }
1474
        LOGGER.info("ourStockAvailability" + ourStockAvailability);
27768 tejbeer 1475
 
32839 amit.gupta 1476
        for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
1477
            int catalogId = catalogIdAggregateValue.getCatalogId();
1478
            Item item = catalogIdItemMap.get(catalogId).get(0);
1479
            TagListing tagListing = taglistingMap.get(item.getId());
1480
            CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1481
            if (!catalogListingMap.containsKey(catalogId)) {
1482
                catalogListingModel = new CatalogListingModel();
1483
                catalogListingModel.setCatalogId(catalogId);
1484
                catalogListingModel.setDp(tagListing.getSellingPrice());
1485
                catalogListingModel.setMop(tagListing.getMop());
1486
                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1487
                if (plannedDetailMap != null) {
26846 tejbeer 1488
 
32839 amit.gupta 1489
                    Integer quantity = plannedDetailMap.get(catalogId);
1490
                    if (quantity != null) {
1491
                        catalogListingModel.setAllocatedQuantity(quantity);
1492
                    }
1493
                }
26846 tejbeer 1494
 
32839 amit.gupta 1495
                if (last15daysMap != null) {
1496
                    Integer last15DaysSale = last15daysMap.get(catalogId);
26846 tejbeer 1497
 
32839 amit.gupta 1498
                    if (last15DaysSale != null) {
1499
                        catalogListingModel.setLast15DaysSale(last15DaysSale);
1500
                    } else {
1501
                        catalogListingModel.setLast15DaysSale(0);
1502
                    }
1503
                } else {
1504
                    catalogListingModel.setLast15DaysSale(0);
1505
                }
26846 tejbeer 1506
 
32839 amit.gupta 1507
                catalogListingModel.setBrand(item.getBrand());
1508
                if (item.getCategoryId() == 10006) {
1509
                    catalogListingModel.setCategoryId(item.getCategoryId());
1510
                }
26846 tejbeer 1511
 
32839 amit.gupta 1512
                Integer ourStock = ourStockAvailability.get(catalogId);
1513
                LOGGER.info("catalogId" + catalogId);
27768 tejbeer 1514
 
32839 amit.gupta 1515
                LOGGER.info("ourStock" + ourStock);
1516
                if (ourStock != null) {
1517
                    catalogListingModel.setOurStockQty(ourStock);
1518
                }
27768 tejbeer 1519
 
32839 amit.gupta 1520
                FocusedModel fm = focusedModelMap.get(catalogId);
1521
                if (fm != null) {
1522
                    catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1523
                    catalogListingModel.setMinimumQty(fm.getMinimumQty());
1524
                    catalogListingModel.setObsRecommendedQty(fm.getObsRecommendedQty());
1525
                    catalogListingModel.setObsMinimumQty(fm.getObsMinimumQty());
26846 tejbeer 1526
 
32839 amit.gupta 1527
                } else {
1528
                    catalogListingModel.setRecommendedQty(0);
1529
                    catalogListingModel.setMinimumQty(0);
29667 tejbeer 1530
 
32839 amit.gupta 1531
                    catalogListingModel.setObsRecommendedQty(0);
1532
                    catalogListingModel.setObsMinimumQty(0);
29667 tejbeer 1533
 
32839 amit.gupta 1534
                }
26846 tejbeer 1535
 
32839 amit.gupta 1536
                catalogListingMap.put(catalogId, catalogListingModel);
26846 tejbeer 1537
 
32839 amit.gupta 1538
            }
1539
            int itemAvailability = 0;
1540
            if (currentStockMap != null) {
1541
                Integer qty = currentStockMap.get(catalogId);
1542
                itemAvailability = qty == null ? 0 : qty;
1543
                catalogListingModel.setStockInHand(itemAvailability);
1544
            } else {
1545
                catalogListingModel.setStockInHand(0);
1546
            }
1547
            Integer inTransitQuantity = itemsInTransit.get(item.getId());
1548
            int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1549
            catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1550
            if (plannedDetailMap != null) {
1551
                if (plannedDetailMap.get(catalogId) != null) {
26846 tejbeer 1552
 
32839 amit.gupta 1553
                    int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1554
                            + catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1555
                    LOGGER.info("remaning" + remaining);
26846 tejbeer 1556
 
32839 amit.gupta 1557
                    if (remaining != 0) {
1558
                        catalogListingModel.setRemaining(remaining);
1559
                    } else {
1560
                        catalogListingModel.setRemaining(0);
1561
                    }
1562
                }
1563
            }
1564
        }
26846 tejbeer 1565
 
32839 amit.gupta 1566
        Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
1567
        if (fofoId > 0) {
1568
            CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1569
            model.addAttribute("retailerName",
1570
                    customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1571
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1572
            model.addAttribute("retailerId", customRetailer.getPartnerId());
1573
            model.addAttribute("counterSize", fs.getCounterSize().toString());
1574
        } else {
1575
            model.addAttribute("counterSize", counterSize.toString());
1576
        }
1577
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
26846 tejbeer 1578
 
32839 amit.gupta 1579
        List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
26846 tejbeer 1580
 
32839 amit.gupta 1581
        Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1582
                Comparator.reverseOrder());
1583
        LOGGER.info("monthlyPlanned" + monthlyPlanned);
1584
        model.addAttribute("catalogTagListings",
1585
                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1586
        model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1587
        model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
1588
        model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1589
        model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
26846 tejbeer 1590
 
32839 amit.gupta 1591
        model.addAttribute("customRetailers", customRetailers);
1592
        model.addAttribute("totalAmount", totalAmount);
1593
        model.addAttribute("monthlyPlanned", monthlyPlanned);
1594
        model.addAttribute("totalPcs", totalPcs);
26846 tejbeer 1595
 
32839 amit.gupta 1596
        UserWallet userWallet = walletService.getUserWallet(fofoId);
26846 tejbeer 1597
 
32839 amit.gupta 1598
        model.addAttribute("userWallet", userWallet);
26846 tejbeer 1599
 
32839 amit.gupta 1600
        return "create-partner-po";
26846 tejbeer 1601
 
32839 amit.gupta 1602
    }
26846 tejbeer 1603
 
32839 amit.gupta 1604
    @RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1605
    public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1606
            throws Exception {
26846 tejbeer 1607
 
32839 amit.gupta 1608
        List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
26846 tejbeer 1609
 
32839 amit.gupta 1610
        List<Item> items = new ArrayList<>();
1611
        for (Item item : selecteditems) {
26846 tejbeer 1612
 
32839 amit.gupta 1613
            TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
26846 tejbeer 1614
 
32839 amit.gupta 1615
            if (tagListing != null) {
1616
                items.add(item);
1617
            }
26846 tejbeer 1618
 
32839 amit.gupta 1619
        }
1620
        model.addAttribute("items", items);
1621
        LOGGER.info("itemIdAndColorMap" + items);
1622
        return "select-item-color";
1623
    }
26846 tejbeer 1624
 
32839 amit.gupta 1625
    List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
34211 vikas.jang 1626
            "niranjan.kala@smartdukaan.com", "amit.gupta@smartdukaan.com", "vikas.jangra@smartdukaan.com");
30003 tejbeer 1627
 
32839 amit.gupta 1628
    @Autowired
1629
    private PositionRepository positionRepository;
30003 tejbeer 1630
 
32839 amit.gupta 1631
    @Autowired
1632
    private PartnerTypeChangeService partnerTypeChangeService;
30003 tejbeer 1633
 
32839 amit.gupta 1634
    @Autowired
1635
    private com.spice.profitmandi.service.transaction.TransactionService transactionService;
30003 tejbeer 1636
 
32839 amit.gupta 1637
    @Autowired
1638
    private CategoryRepository categoryRepository;
30003 tejbeer 1639
 
32839 amit.gupta 1640
    @Autowired
1641
    private BrandLimitRepository brandLimitRepository;
30044 tejbeer 1642
 
31663 amit.gupta 1643
 
32839 amit.gupta 1644
    private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING,
1645
            OrderStatus.ACCEPTED);
30003 tejbeer 1646
 
32839 amit.gupta 1647
    public static final Map<String, Double> Brand_Amount_Limit = new HashMap<>();
30003 tejbeer 1648
 
32839 amit.gupta 1649
    static {
30044 tejbeer 1650
 
32839 amit.gupta 1651
        Brand_Amount_Limit.put("accessories", 10000.00);
1652
        Brand_Amount_Limit.put("TV", 27000.00);
1653
    }
30003 tejbeer 1654
 
33806 tejus.loha 1655
 
32839 amit.gupta 1656
    @RequestMapping(value = "/getPartnersBrandWiseDetail", method = RequestMethod.GET)
1657
    public String getPartnersBrandWiseDetail(HttpServletRequest request, Model model) throws Exception {
30003 tejbeer 1658
 
32839 amit.gupta 1659
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1660
        String email = loginDetails.getEmailId();
30003 tejbeer 1661
 
34035 ranu 1662
        List<String> brands = ProfitMandiConstants.BRANDS;
30003 tejbeer 1663
 
32839 amit.gupta 1664
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1665
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
30003 tejbeer 1666
 
32839 amit.gupta 1667
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
30003 tejbeer 1668
 
32839 amit.gupta 1669
        Map<Integer, Map<String, Double>> fofoIdBrandAmountMap = new HashMap<>();
35484 ranu 1670
        Map<Integer, Map<String, Double>> fofoIdBrandQtyMap = new HashMap<>();
30003 tejbeer 1671
 
32839 amit.gupta 1672
        Map<Integer, InStockAccessoriesTvFofoIdModel> inStockAccessTv = new HashMap<>();
1673
        Map<Integer, InStockAccessoriesTvFofoIdModel> pendingIndentAccessTv = new HashMap<>();
1674
        Map<Integer, InStockAccessoriesTvFofoIdModel> grnPendingAccessTvOrders = new HashMap<>();
35490 ranu 1675
 
1676
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> inStockQtyAccessTv = new HashMap<>();
1677
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> pendingIndentQtyAccessTv = new HashMap<>();
1678
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> grnPendingQtyAccessTvOrders = new HashMap<>();
32839 amit.gupta 1679
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1680
        Map<Integer, CustomRetailer> customRetailers = new HashMap<>();
1681
        Map<Integer, PartnerType> fofoIdPartnerTypeMap = new HashMap<>();
30003 tejbeer 1682
 
32839 amit.gupta 1683
        if (fofoIds != null && fofoIds.size() > 0) {
1684
            List<Integer> fofoIdList = new ArrayList<>(fofoIds);
30003 tejbeer 1685
 
32839 amit.gupta 1686
            Map<Integer, ActivationType> partnerActivationType = fofoStoreRepository.selectByRetailerIds(fofoIdList)
1687
                    .stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getActivationType()));
1688
            //Only L3 and above can change the accessType
35395 amit 1689
            boolean canChangeActionType = positionRepository.selectAllByAuthUserId(authUser.getId())
32839 amit.gupta 1690
                    .stream().filter(x -> x.getEscalationType().isGreaterThanEqualTo(EscalationType.L3)).count() > 0;
1691
            model.addAttribute("canChangeActivationType", canChangeActionType);
1692
            model.addAttribute("partnerActivationType", partnerActivationType);
1693
            model.addAttribute("activationTypes", ActivationType.values());
30046 tejbeer 1694
 
32839 amit.gupta 1695
            Map<Integer, FofoReportingModel> partnerSalesHeadersMap = csService.getPartnerIdSalesHeaders();
30046 tejbeer 1696
 
32839 amit.gupta 1697
            model.addAttribute("partnerSalesHeadersMap", partnerSalesHeadersMap);
30003 tejbeer 1698
 
32839 amit.gupta 1699
            Map<Integer, Map<String, Float>> partnerBrandLimitMap = brandLimitRepository.selectAllPartnerBrandLimit()
1700
                    .stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1701
                            Collectors.toMap(x -> x.getBrand(), x -> x.getBrandLimit())));
30044 tejbeer 1702
 
32839 amit.gupta 1703
            model.addAttribute("partnerBrandLimitMap", partnerBrandLimitMap);
1704
            customRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1705
                    .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1706
            Map<Integer, Map<String, Double>> inStockBrandModel;
35484 ranu 1707
            Map<Integer, Map<String, Double>> inStockBrandModelQty;
32839 amit.gupta 1708
            Map<Integer, Map<String, Double>> pendingIndent;
35484 ranu 1709
            Map<Integer, Map<String, Double>> pendingIndentQty;
32839 amit.gupta 1710
            Map<Integer, Map<String, Double>> grnPendingOrders;
35484 ranu 1711
            Map<Integer, Map<String, Double>> grnPendingOrdersQty;
30044 tejbeer 1712
 
32839 amit.gupta 1713
            // mobile
35490 ranu 1714
            List<InStockBrandFofoIdModel> inStockBrandFofoIdModels = currentInventorySnapshotRepository.selectSumInStockMobiletabletGroupByBrand(fofoIdList);
1715
 
1716
            inStockBrandModel = inStockBrandFofoIdModels
32839 amit.gupta 1717
                    .stream()
1718
                    .collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1719
                            Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1720
                                    Collectors.summingDouble(InStockBrandFofoIdModel::getAmount))));
30003 tejbeer 1721
 
35490 ranu 1722
            inStockBrandModelQty = inStockBrandFofoIdModels
35484 ranu 1723
                    .stream()
1724
                    .collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1725
                            Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1726
                                    Collectors.summingDouble(InStockBrandFofoIdModel::getQty))));
1727
 
35490 ranu 1728
            List<Order> pendingIndentOrders = transactionService.getInTransitOrders(fofoIdList);
1729
 
1730
            pendingIndent = pendingIndentOrders.stream()
32839 amit.gupta 1731
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1732
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1733
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1734
                                    Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
30003 tejbeer 1735
 
35490 ranu 1736
 
1737
            pendingIndentQty = pendingIndentOrders.stream()
35484 ranu 1738
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1739
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1740
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1741
                                    Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));
1742
 
35490 ranu 1743
 
1744
            List<Order> grnPendingOrderList = orderRepository.selectPendingGrnOrders(fofoIdList);
1745
 
1746
            grnPendingOrders = grnPendingOrderList.stream()
32839 amit.gupta 1747
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1748
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1749
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1750
                                    Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
35490 ranu 1751
            grnPendingOrdersQty = grnPendingOrderList.stream()
35484 ranu 1752
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1753
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1754
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1755
                                    Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));
30003 tejbeer 1756
 
32839 amit.gupta 1757
            // accessories
1758
            inStockAccessTv = currentInventorySnapshotRepository.selectSumInStockAccessoriesAndTv(fofoIdList).stream()
1759
                    .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1760
 
32839 amit.gupta 1761
            pendingIndentAccessTv = orderRepository.selectAllPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1762
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1763
 
32839 amit.gupta 1764
            grnPendingAccessTvOrders = orderRepository.selectAllGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1765
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1766
 
35490 ranu 1767
 
1768
            inStockQtyAccessTv = currentInventorySnapshotRepository.selectQtySumInStockAccessoriesAndTv(fofoIdList).stream()
1769
                    .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1770
 
1771
            pendingIndentQtyAccessTv = orderRepository.selectAllQtyPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1772
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1773
 
1774
            grnPendingQtyAccessTvOrders = orderRepository.selectAllQtyGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1775
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1776
 
35462 amit 1777
            // Bulk fetch partner types to avoid N+1 queries
1778
            fofoIdPartnerTypeMap = partnerTypeChangeService.getTypesForFofoIds(new ArrayList<>(customRetailers.keySet()), LocalDate.now());
1779
 
32839 amit.gupta 1780
            for (Entry<Integer, CustomRetailer> customRetailer : customRetailers.entrySet()) {
1781
                Map<String, Double> stockBrand = inStockBrandModel.get(customRetailer.getKey());
35484 ranu 1782
                Map<String, Double> stockBrandQty = inStockBrandModelQty.get(customRetailer.getKey());
32839 amit.gupta 1783
                Map<String, Double> pendingIndentBrand = pendingIndent.get(customRetailer.getKey());
35484 ranu 1784
                Map<String, Double> pendingIndentBrandQty = pendingIndentQty.get(customRetailer.getKey());
32839 amit.gupta 1785
                Map<String, Double> grnBrand = grnPendingOrders.get(customRetailer.getKey());
35484 ranu 1786
                Map<String, Double> grnBrandQty = grnPendingOrdersQty.get(customRetailer.getKey());
32839 amit.gupta 1787
                double totalAmount = 0;
35484 ranu 1788
                double totalQty = 0;
30024 tejbeer 1789
 
32839 amit.gupta 1790
                Map<String, Double> brandAmountMap = new HashMap<>();
35484 ranu 1791
                Map<String, Double> brandQtyMap = new HashMap<>();
32839 amit.gupta 1792
                for (String brand : brands) {
30024 tejbeer 1793
 
32839 amit.gupta 1794
                    double stockValue = 0;
35484 ranu 1795
                    double stockQty = 0;
32839 amit.gupta 1796
                    double pendingValue = 0;
35484 ranu 1797
                    double pendingQty = 0;
32839 amit.gupta 1798
                    double grnValue = 0;
35484 ranu 1799
                    double grnQty = 0;
32839 amit.gupta 1800
                    if (stockBrand != null) {
30024 tejbeer 1801
 
32839 amit.gupta 1802
                        if (stockBrand.get(brand) != null) {
1803
                            stockValue = stockBrand.get(brand);
1804
                        }
1805
                    }
30024 tejbeer 1806
 
35484 ranu 1807
                    if (stockBrandQty != null) {
1808
 
1809
                        if (stockBrandQty.get(brand) != null) {
1810
                            stockQty = stockBrandQty.get(brand);
1811
                        }
1812
                    }
1813
 
32839 amit.gupta 1814
                    if (pendingIndentBrand != null) {
1815
                        if (pendingIndentBrand.get(brand) != null) {
1816
                            pendingValue = pendingIndentBrand.get(brand);
1817
                        }
1818
                    }
35484 ranu 1819
                    if (pendingIndentBrandQty != null) {
1820
                        if (pendingIndentBrandQty.get(brand) != null) {
1821
                            pendingQty = pendingIndentBrandQty.get(brand);
1822
                        }
1823
                    }
30024 tejbeer 1824
 
32839 amit.gupta 1825
                    if (grnBrand != null) {
1826
                        if (grnBrand.get(brand) != null) {
1827
                            grnValue = grnBrand.get(brand);
1828
                        }
1829
                    }
30024 tejbeer 1830
 
35484 ranu 1831
                    if (grnBrandQty != null) {
1832
                        if (grnBrandQty.get(brand) != null) {
1833
                            grnQty = grnBrandQty.get(brand);
1834
                        }
1835
                    }
1836
 
32839 amit.gupta 1837
                    totalAmount = stockValue + pendingValue + grnValue;
30024 tejbeer 1838
 
35484 ranu 1839
                    totalQty = stockQty + pendingQty + grnQty;
1840
 
32839 amit.gupta 1841
                    brandAmountMap.put(brand, totalAmount);
30024 tejbeer 1842
 
35484 ranu 1843
                    brandQtyMap.put(brand, totalQty);
1844
 
32839 amit.gupta 1845
                }
30024 tejbeer 1846
 
32839 amit.gupta 1847
                fofoIdBrandAmountMap.put(customRetailer.getKey(), brandAmountMap);
35484 ranu 1848
                fofoIdBrandQtyMap.put(customRetailer.getKey(), brandQtyMap);
30024 tejbeer 1849
 
32839 amit.gupta 1850
            }
30024 tejbeer 1851
 
32839 amit.gupta 1852
            List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
1853
                    .selectAll(new ArrayList<>(fofoIdList), LocalDate.now().minusDays(1));
1854
            if (!partnerDailyInvestments.isEmpty()) {
1855
                partnerDailyInvestmentMap = partnerDailyInvestments.stream()
1856
                        .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1857
            }
30024 tejbeer 1858
 
32839 amit.gupta 1859
        }
33806 tejus.loha 1860
        Map<Integer, MonthlyTarget> fofoIdMonthlyTargetMap = monthlyTargetRepository.selectByDateAndFofoIds(YearMonth.now(), new ArrayList<>(fofoIds)).stream()
1861
                .collect(Collectors.toMap(MonthlyTarget::getFofoId, x -> x,
1862
                        (existing, replacement) -> replacement  // Keep the last entry
1863
                ));
1864
 
1865
        Map<Integer, Float> fofoMTDSaleMap = fofoOrderRepository.selectSaleSumGroupByFofoIds(YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now());
1866
 
1867
        Map<Integer, Double> currentMonthTillDateRetailerPOValueMap = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(new ArrayList<>(fofoIds),
1868
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
1869
                YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
1870
 
35811 amit 1871
        Map<Integer, BulkCreditSummary> bulkSummaryMap = sdCreditService.getCreditSummaryBulk();
33812 tejus.loha 1872
        Map<Integer, BigDecimal> totalDueMap = new HashMap<>();
35811 amit 1873
        for (int fofoId : fofoIds) {
1874
            BulkCreditSummary summary = bulkSummaryMap.get(fofoId);
1875
            if (summary != null) {
1876
                totalDueMap.put(fofoId, summary.getTotalDue());
33812 tejus.loha 1877
            }
1878
        }
1879
 
33813 tejus.loha 1880
 
32839 amit.gupta 1881
        //Only L3 and above can change the activationType
30024 tejbeer 1882
 
32839 amit.gupta 1883
        model.addAttribute("customRetailers", customRetailers);
33812 tejus.loha 1884
        model.addAttribute("totalDueMap", totalDueMap);
33806 tejus.loha 1885
        model.addAttribute("fofoMTDSaleMap", fofoMTDSaleMap);
1886
        model.addAttribute("fofoIdMonthlyTargetMap", fofoIdMonthlyTargetMap);
1887
        model.addAttribute("currentMonthTillDateRetailerPOValueMap", currentMonthTillDateRetailerPOValueMap);
30003 tejbeer 1888
 
34759 amit.gupta 1889
        //LOGGER.info("fofoIdBrandAmountMap" + fofoIdBrandAmountMap);
30003 tejbeer 1890
 
32839 amit.gupta 1891
        model.addAttribute("partnerDailyInvestmentMap", partnerDailyInvestmentMap);
30003 tejbeer 1892
 
32839 amit.gupta 1893
        model.addAttribute("brands", brands);
30003 tejbeer 1894
 
32839 amit.gupta 1895
        model.addAttribute("brandAmountLimit", Brand_Amount_Limit);
1896
        model.addAttribute("fofoIdBrandAmountMap", fofoIdBrandAmountMap);
35484 ranu 1897
        model.addAttribute("fofoIdBrandQtyMap", fofoIdBrandQtyMap);
30003 tejbeer 1898
 
32839 amit.gupta 1899
        model.addAttribute("inStockAccessTv", inStockAccessTv);
1900
        model.addAttribute("pendingIndentAccessTv", pendingIndentAccessTv);
1901
        model.addAttribute("grnPendingAccessTvOrders", grnPendingAccessTvOrders);
35490 ranu 1902
        model.addAttribute("inStockQtyAccessTv", inStockQtyAccessTv);
1903
        model.addAttribute("pendingIndentQtyAccessTv", pendingIndentQtyAccessTv);
1904
        model.addAttribute("grnPendingQtyAccessTvOrders", grnPendingQtyAccessTvOrders);
32839 amit.gupta 1905
        model.addAttribute("fofoIdPartnerTypeMap", fofoIdPartnerTypeMap);
30003 tejbeer 1906
 
1907
 
32839 amit.gupta 1908
        return "partner-brandwise-detail";
1909
    }
30046 tejbeer 1910
 
32839 amit.gupta 1911
    @RequestMapping(value = "/changeActivationType", method = RequestMethod.POST)
1912
    public String changeActivationType(HttpServletRequest request, @RequestParam String code,
1913
                                       @RequestParam ActivationType activationType, Model model) throws Exception {
30046 tejbeer 1914
 
32839 amit.gupta 1915
        FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(code);
30046 tejbeer 1916
 
32839 amit.gupta 1917
        fofoStore.setActivationType(activationType);
30046 tejbeer 1918
 
32839 amit.gupta 1919
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1920
        return "response";
30046 tejbeer 1921
 
32839 amit.gupta 1922
    }
30017 amit.gupta 1923
 
32839 amit.gupta 1924
    @RequestMapping(value = "/createPo", method = RequestMethod.POST)
1925
    public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1926
            throws Exception {
1927
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1928
        SuggestedPo mp = new SuggestedPo();
1929
        mp.setFofoId(monthlyPoModel.getFofoId());
1930
        mp.setCreateTimestamp(LocalDateTime.now());
1931
        mp.setStatus("open");
1932
        mp.setAuthId(loginDetails.getEmailId());
1933
        suggestedPoRepository.persist(mp);
30017 amit.gupta 1934
 
32839 amit.gupta 1935
        for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1936
            SuggestedPoDetail mpd = new SuggestedPoDetail();
1937
            mpd.setItemId(poId.getItemId());
1938
            mpd.setQuantity(poId.getQty());
1939
            mpd.setUpdatedTimestamp(LocalDateTime.now());
1940
            mpd.setPoId(mp.getId());
1941
            suggestedPoDetailRepository.persist(mpd);
1942
        }
30017 amit.gupta 1943
 
32839 amit.gupta 1944
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
1945
        sendNotificationModel.setCampaignName("Alert");
1946
        sendNotificationModel.setMessage("Suggested Po");
1947
        sendNotificationModel.setType("url");
1948
        sendNotificationModel.setTitle("Alert");
1949
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
1950
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1951
        sendNotificationModel.setMessageType(MessageType.notification);
1952
        int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
30017 amit.gupta 1953
 
32839 amit.gupta 1954
        sendNotificationModel.setUserIds(Arrays.asList(userId));
1955
        notificationService.sendNotification(sendNotificationModel);
1956
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
30017 amit.gupta 1957
 
32839 amit.gupta 1958
        return "response";
1959
    }
30003 tejbeer 1960
 
34087 ranu 1961
 
34437 ranu 1962
    @RequestMapping(value = "/createSuggestedPo", method = RequestMethod.POST)
1963
    public String createSuggestedPo(HttpServletRequest request, @RequestBody List<SuggestedPoCatalogModel> poCatalogModel, @RequestParam int fofoId, Model model)
1964
            throws Exception {
1965
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1966
        List<SuggestedPo> suggestedPos = suggestedPoRepository.selectAllOpenPoByFofoId(fofoId);
1967
        for (SuggestedPo suggestedPo : suggestedPos) {
1968
            suggestedPo.setStatus("closed");
1969
        }
1970
        SuggestedPo mp = new SuggestedPo();
1971
        mp.setFofoId(fofoId);
1972
        mp.setCreateTimestamp(LocalDateTime.now());
1973
        mp.setStatus("open");
1974
        mp.setAuthId(loginDetails.getEmailId());
1975
        suggestedPoRepository.persist(mp);
1976
 
1977
        for (SuggestedPoCatalogModel catalogModel : poCatalogModel) {
1978
            SuggestedPoDetail mpd = new SuggestedPoDetail();
34449 ranu 1979
            mpd.setItemId(catalogModel.getItemId());
34437 ranu 1980
            mpd.setQuantity(catalogModel.getQty());
1981
            mpd.setUpdatedTimestamp(LocalDateTime.now());
1982
            mpd.setPoId(mp.getId());
1983
            suggestedPoDetailRepository.persist(mpd);
1984
        }
1985
 
1986
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
1987
        sendNotificationModel.setCampaignName("Alert");
1988
        sendNotificationModel.setMessage("Suggested Po");
1989
        sendNotificationModel.setType("url");
1990
        sendNotificationModel.setTitle("Alert");
1991
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
1992
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1993
        sendNotificationModel.setMessageType(MessageType.notification);
1994
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1995
 
1996
        sendNotificationModel.setUserIds(Arrays.asList(userId));
1997
        notificationService.sendNotification(sendNotificationModel);
1998
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1999
 
2000
        return "response";
2001
    }
2002
 
2003
 
34087 ranu 2004
    @RequestMapping(value = "/getPartnerShortageStockDetail", method = RequestMethod.GET)
2005
    public String getPartnerShortageStockDetail(HttpServletRequest request,
34098 ranu 2006
                                                @RequestParam(required = false, defaultValue = "") String brand, @RequestParam int fofoId, Model model)
32839 amit.gupta 2007
            throws Exception {
30003 tejbeer 2008
 
32839 amit.gupta 2009
        Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService
2010
                .getSaholicPOItems();
30003 tejbeer 2011
 
32839 amit.gupta 2012
        List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
2013
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2014
        Map<Integer, Integer> processingOrderMap = null;
2015
        Map<Integer, Integer> catalogIdAndQtyMap = null;
2016
        Map<Integer, Integer> grnPendingOrdersMap = null;
30044 tejbeer 2017
 
34490 ranu 2018
        Map<String, Set<PartnerStockDetailModel>> brandToUniqueItemsMap = new HashMap<>();
34449 ranu 2019
 
34490 ranu 2020
        List<PartnerStockDetailModel> inStocks = new ArrayList<>();
2021
        Map<String, PartnerStockDetailModel> inStocksDescriptionModelMap = new HashMap<>();
30044 tejbeer 2022
 
34490 ranu 2023
        List<PartnerStockDetailModel> grnPendings = new ArrayList<>();
2024
        Map<String, PartnerStockDetailModel> grnPendingsDescriptionModelMap = new HashMap<>();
30044 tejbeer 2025
 
34449 ranu 2026
 
34490 ranu 2027
        List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();
2028
        Map<String, PartnerStockDetailModel> pendingIndentsDescriptionModelMap = new HashMap<>();
30003 tejbeer 2029
 
32839 amit.gupta 2030
        Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
2031
                .stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
30003 tejbeer 2032
 
34425 ranu 2033
 
32839 amit.gupta 2034
        if (!currentInventorySnapshot.isEmpty()) {
34425 ranu 2035
            catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
2036
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2037
                            Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
34490 ranu 2038
            inStocks.addAll(getBrandItemwiseDetail(brand, catalogIdAndQtyMap));
34449 ranu 2039
            inStocksDescriptionModelMap = inStocks.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
32839 amit.gupta 2040
        }
34449 ranu 2041
 
32839 amit.gupta 2042
        Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
2043
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2044
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2045
        if (!grnPendingOrders.isEmpty()) {
34425 ranu 2046
            grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
2047
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2048
                            Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
34490 ranu 2049
            grnPendings.addAll(getBrandItemwiseDetail(brand, grnPendingOrdersMap));
34449 ranu 2050
            grnPendingsDescriptionModelMap = grnPendings.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
30003 tejbeer 2051
 
32839 amit.gupta 2052
        }
30003 tejbeer 2053
 
32839 amit.gupta 2054
        Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
2055
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2056
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2057
        if (!processingOrder.isEmpty()) {
34425 ranu 2058
            processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
2059
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2060
                            Collectors.summingInt(x -> processingOrder.get(x.getId()))));
34490 ranu 2061
            pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));
34449 ranu 2062
            pendingIndentsDescriptionModelMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
30003 tejbeer 2063
 
32839 amit.gupta 2064
        }
30003 tejbeer 2065
 
32839 amit.gupta 2066
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
2067
                .collect(Collectors.toList());
2068
        LOGGER.info("regionIds" + regionIds);
2069
        if (regionIds.size() == 0) {
2070
            LOGGER.info("No region found for partner {}", fofoId);
30003 tejbeer 2071
 
32839 amit.gupta 2072
        }
34456 ranu 2073
 
2074
//        this code is using for focusedModel()
32839 amit.gupta 2075
        Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository
2076
                .selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,
2077
                        Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
30003 tejbeer 2078
 
32839 amit.gupta 2079
        for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
2080
            List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());
30003 tejbeer 2081
 
32839 amit.gupta 2082
            if (brand.equals("undefined") || items.get(0).getBrand().equals(brand)) {
30003 tejbeer 2083
 
32839 amit.gupta 2084
                FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(), entry.getKey(),
2085
                        processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2086
                        warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2087
 
32839 amit.gupta 2088
                focusedModelShortageList.add(fm);
2089
            } else if (brand.equals("accessories")) {
30003 tejbeer 2090
 
32839 amit.gupta 2091
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2092
                    if (items.get(0).getCategoryId() != 0) {
2093
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30003 tejbeer 2094
 
32839 amit.gupta 2095
                        if (category.getParentCategoryId() == 10011) {
2096
                            FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2097
                                    entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2098
                                    warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2099
 
32839 amit.gupta 2100
                            focusedModelShortageList.add(fm);
30003 tejbeer 2101
 
32839 amit.gupta 2102
                        }
2103
                    }
30003 tejbeer 2104
 
32839 amit.gupta 2105
                }
30003 tejbeer 2106
 
32839 amit.gupta 2107
            } else if (brand.equals("TV")) {
30003 tejbeer 2108
 
32839 amit.gupta 2109
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2110
                    LOGGER.info("items.get(0).getCategoryId()" + items.get(0).getCategoryId());
2111
                    if (items.get(0).getCategoryId() != 0) {
30003 tejbeer 2112
 
32839 amit.gupta 2113
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30003 tejbeer 2114
 
32839 amit.gupta 2115
                        if (category.getParentCategoryId() == 14200) {
2116
                            FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2117
                                    entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2118
                                    warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2119
 
32839 amit.gupta 2120
                            focusedModelShortageList.add(fm);
30003 tejbeer 2121
 
32839 amit.gupta 2122
                        }
2123
                    }
30003 tejbeer 2124
 
32839 amit.gupta 2125
                }
30003 tejbeer 2126
 
32839 amit.gupta 2127
            }
30003 tejbeer 2128
 
32839 amit.gupta 2129
        }
30003 tejbeer 2130
 
34490 ranu 2131
        List<PartnerStockDetailModel> allStockItems = new ArrayList<>();
34449 ranu 2132
        allStockItems.addAll(inStocks);
2133
        allStockItems.addAll(grnPendings);
2134
        allStockItems.addAll(pendingIndents);
34760 amit.gupta 2135
        //LOGGER.info("allStockItems {}", allStockItems);
34449 ranu 2136
        brandToUniqueItemsMap =
2137
                allStockItems.stream().collect(
2138
                        Collectors.groupingBy(
34490 ranu 2139
                                PartnerStockDetailModel::getBrand,
34449 ranu 2140
                                Collectors.toSet()
2141
                        )
2142
                );
30003 tejbeer 2143
 
34449 ranu 2144
 
32839 amit.gupta 2145
        model.addAttribute("focusedModelShortageList", focusedModelShortageList);
30044 tejbeer 2146
 
32839 amit.gupta 2147
        model.addAttribute("inStocks", inStocks);
34449 ranu 2148
        model.addAttribute("inStocksDescriptionModelMap", inStocksDescriptionModelMap);
30044 tejbeer 2149
 
34449 ranu 2150
        model.addAttribute("brandToUniqueItemsMap", brandToUniqueItemsMap);
34490 ranu 2151
        model.addAttribute("fofoId", fofoId);
34425 ranu 2152
 
32839 amit.gupta 2153
        model.addAttribute("grnPendings", grnPendings);
34449 ranu 2154
        model.addAttribute("grnPendingsDescriptionModelMap", grnPendingsDescriptionModelMap);
30044 tejbeer 2155
 
32839 amit.gupta 2156
        model.addAttribute("pendingIndents", pendingIndents);
34449 ranu 2157
        model.addAttribute("pendingIndentsDescriptionModelMap", pendingIndentsDescriptionModelMap);
30044 tejbeer 2158
 
32839 amit.gupta 2159
        model.addAttribute("customRetailer", customRetailer);
30044 tejbeer 2160
 
32839 amit.gupta 2161
        model.addAttribute("brand", brand);
30044 tejbeer 2162
 
32839 amit.gupta 2163
        if (brand.equals("undefined")) {
30044 tejbeer 2164
 
32839 amit.gupta 2165
            Map<String, List<FocusedModelShortageModel>> focusedModelShortageBrandMap = focusedModelShortageList
2166
                    .stream().collect(Collectors.groupingBy(x -> x.getBrandName()));
30044 tejbeer 2167
 
34490 ranu 2168
            Map<String, List<PartnerStockDetailModel>> inStockBrandMap = inStocks.stream()
32839 amit.gupta 2169
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2170
 
32839 amit.gupta 2171
            LOGGER.info("inStockBrandMap" + inStockBrandMap);
30044 tejbeer 2172
 
34490 ranu 2173
            Map<String, List<PartnerStockDetailModel>> grnPendingBrandMap = grnPendings.stream()
32839 amit.gupta 2174
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2175
 
32839 amit.gupta 2176
            LOGGER.info("grnPendingBrandMap" + grnPendingBrandMap);
30044 tejbeer 2177
 
34490 ranu 2178
            Map<String, List<PartnerStockDetailModel>> pendingIndentBrandMap = pendingIndents.stream()
32839 amit.gupta 2179
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2180
 
32839 amit.gupta 2181
            LOGGER.info("pendingIndentBrandMap" + pendingIndentBrandMap);
30044 tejbeer 2182
 
32839 amit.gupta 2183
            model.addAttribute("inStockBrandMap", inStockBrandMap);
30044 tejbeer 2184
 
32839 amit.gupta 2185
            model.addAttribute("grnPendingBrandMap", grnPendingBrandMap);
30044 tejbeer 2186
 
32839 amit.gupta 2187
            model.addAttribute("focusedModelShortageBrandMap", focusedModelShortageBrandMap);
30044 tejbeer 2188
 
32839 amit.gupta 2189
            model.addAttribute("pendingIndentBrandMap", pendingIndentBrandMap);
30003 tejbeer 2190
 
32839 amit.gupta 2191
        }
34035 ranu 2192
 
34087 ranu 2193
        return "partner-stock-detail";
2194
 
2195
    }
2196
 
34397 ranu 2197
 
34449 ranu 2198
    @RequestMapping(value = "/getPoCatalogsItems", method = RequestMethod.GET)
34581 ranu 2199
    public String getPoCatalogsItems(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, @RequestParam float price, Model model)
34449 ranu 2200
            throws Exception {
2201
        List<Item> poItems = itemRepository.selectAllByCatalogItemId(catalogId);
34581 ranu 2202
 
2203
        List<Integer> itemIds = poItems.stream().map(x -> x.getId()).collect(Collectors.toList());
2204
 
2205
        Map<Integer, Integer> saholicInventoryMap = saholicInventoryService.getTotalAvailabilityByItemIds(itemIds);
2206
 
2207
        Set<Integer> availableStockItemIds = saholicInventoryMap.entrySet().stream()
2208
                .filter(x -> x.getValue() > 0)
2209
                .map(Map.Entry::getKey)
2210
                .collect(Collectors.toSet());
2211
 
2212
        List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == warehouseId)).collect(Collectors.toList());
2213
 
2214
        Set<Integer> intransitItemIds = warehouseIntransitDataModels.stream()
2215
                .filter(x -> x.getQty() > 0)
2216
                .map(WarehouseIntransitDataModel::getItemId)
2217
                .collect(Collectors.toSet());
2218
 
2219
        // Filter intransitItemIds to only those in itemIds
2220
        Set<Integer> intransitItemIdsFiltered = new HashSet<>(intransitItemIds);
2221
        intransitItemIdsFiltered.retainAll(itemIds);
2222
 
2223
        Set<Integer> itemIdsWithBothStocks = new HashSet<>();
2224
        itemIdsWithBothStocks.addAll(intransitItemIdsFiltered); // keeps only the common ones
2225
        itemIdsWithBothStocks.addAll(availableStockItemIds); // keeps only the common ones
2226
 
2227
        LOGGER.info("itemIds {}", itemIds);
2228
        LOGGER.info("itemIdsWithBothStocks {}", itemIdsWithBothStocks);
2229
        LOGGER.info("availableStockItemIds {}", availableStockItemIds);
2230
        LOGGER.info("intransitItemIdsFiltered {}", intransitItemIdsFiltered);
35782 ranu 2231
        List<Item> instockItems = new ArrayList<>();
2232
        if (itemIdsWithBothStocks.isEmpty() && availableStockItemIds.isEmpty() && intransitItemIdsFiltered.isEmpty()) {
2233
            instockItems = itemRepository.selectByIds(itemIds);
2234
        } else {
2235
            instockItems = itemRepository.selectByIds(itemIdsWithBothStocks);
2236
        }
34581 ranu 2237
 
35782 ranu 2238
 
34581 ranu 2239
        model.addAttribute("poItems", instockItems);
34449 ranu 2240
        model.addAttribute("price", price);
2241
 
2242
        return "po-catalog-items";
2243
    }
2244
 
2245
 
34490 ranu 2246
    @RequestMapping(value = "/getItemsByCatalog", method = RequestMethod.GET)
2247
    public ResponseEntity<?> getItemsByCatalog(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int fofoId, Model model)
2248
            throws Exception {
2249
        List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
34495 ranu 2250
        Map<Integer, Item> itemMap = items.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
34490 ranu 2251
        Set<Integer> itemSet = items.stream().map(x -> x.getId()).collect(Collectors.toSet());
2252
        List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemSet);
35771 ranu 2253
 
2254
        // Get activated but not sold inventory items for this fofoId
2255
        List<InventoryItem> activatedNotSoldItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
2256
 
2257
        // Group activated items by itemId with their serial numbers
2258
        Map<Integer, List<String>> activatedItemImeiMap = activatedNotSoldItems.stream()
2259
                .collect(Collectors.groupingBy(
2260
                        InventoryItem::getItemId,
2261
                        Collectors.mapping(InventoryItem::getSerialNumber, Collectors.toList())
2262
                ));
2263
 
34495 ranu 2264
        List<InStockItemDetailModel> inStockItemDetailModels = new ArrayList<>();
35776 ranu 2265
 
2266
        // Add in-stock items
34495 ranu 2267
        for (CurrentInventorySnapshot snap : currentInventorySnapshots) {
2268
            InStockItemDetailModel inStockItemDetailModel = new InStockItemDetailModel();
2269
            inStockItemDetailModel.setAvailability(snap.getAvailability());
2270
            inStockItemDetailModel.setItemId(snap.getItemId());
2271
            inStockItemDetailModel.setCatalogId(itemMap.get(snap.getItemId()).getCatalogItemId());
2272
            inStockItemDetailModel.setItemDescription(itemMap.get(snap.getItemId()).getItemDescription());
2273
            inStockItemDetailModel.setFofoId(snap.getFofoId());
35776 ranu 2274
            inStockItemDetailModel.setStockType("IN_STOCK");
35771 ranu 2275
            // Check if this item has any activated but not sold IMEIs and set the IMEI list
2276
            List<String> activatedImeis = activatedItemImeiMap.get(snap.getItemId());
2277
            if (activatedImeis != null && !activatedImeis.isEmpty()) {
2278
                inStockItemDetailModel.setHasActivatedImei(true);
2279
                inStockItemDetailModel.setActivatedImeis(activatedImeis);
2280
            }
34495 ranu 2281
            inStockItemDetailModels.add(inStockItemDetailModel);
2282
        }
2283
 
35776 ranu 2284
        // Get GRN pending orders for this fofoId and filter by catalog items
2285
        Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
2286
                .filter(x -> itemSet.contains(x.getLineItem().getItemId()))
2287
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2288
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2289
 
2290
        // Add GRN pending items
2291
        for (Map.Entry<Integer, Integer> entry : grnPendingOrders.entrySet()) {
2292
            int itemId = entry.getKey();
2293
            int qty = entry.getValue();
2294
            if (itemMap.containsKey(itemId)) {
2295
                InStockItemDetailModel grnModel = new InStockItemDetailModel();
2296
                grnModel.setAvailability(qty);
2297
                grnModel.setItemId(itemId);
2298
                grnModel.setCatalogId(itemMap.get(itemId).getCatalogItemId());
2299
                grnModel.setItemDescription(itemMap.get(itemId).getItemDescription());
2300
                grnModel.setFofoId(fofoId);
2301
                grnModel.setStockType("GRN_PENDING");
2302
                inStockItemDetailModels.add(grnModel);
2303
            }
2304
        }
2305
 
34495 ranu 2306
        return responseSender.ok(inStockItemDetailModels);
34490 ranu 2307
    }
34449 ranu 2308
 
35765 ranu 2309
    @RequestMapping(value = "/indent/getOurStockDetails", method = RequestMethod.GET)
2310
    public ResponseEntity<?> getOurStockDetails(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, Model model)
2311
            throws Exception {
2312
        try {
2313
            // Get all items by catalogId
2314
            List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
2315
            List<Integer> itemIds = items.stream().map(Item::getId).collect(Collectors.toList());
2316
 
2317
            if (itemIds.isEmpty()) {
2318
                return responseSender.ok(Collections.emptyList());
2319
            }
2320
 
2321
            // Get saholic stock for these items
2322
            Map<Integer, List<WarehouseItemQtyModel>> stockMap = saholicInventoryService.getSaholicStock(warehouseId, itemIds);
2323
 
2324
            // Build result with item description and qty where netAvailability > 0
2325
            List<Map<String, Object>> result = new ArrayList<>();
2326
            for (Item item : items) {
2327
                List<WarehouseItemQtyModel> stockList = stockMap.get(item.getId());
2328
                if (stockList != null && !stockList.isEmpty()) {
2329
                    int totalNetAvailability = stockList.stream()
2330
                            .mapToInt(WarehouseItemQtyModel::getNetAvailability)
2331
                            .sum();
2332
                    if (totalNetAvailability > 0) {
2333
                        Map<String, Object> itemDetail = new HashMap<>();
2334
                        itemDetail.put("itemId", item.getId());
2335
                        itemDetail.put("color", item.getColor());
2336
                        itemDetail.put("itemDescription", item.getItemDescription());
2337
                        itemDetail.put("qty", totalNetAvailability);
2338
                        result.add(itemDetail);
2339
                    }
2340
                }
2341
            }
2342
 
2343
            return responseSender.ok(result);
2344
        } catch (Exception e) {
2345
            LOGGER.error("Error getting our stock details for catalogId: {} warehouseId: {}", catalogId, warehouseId, e);
2346
            return responseSender.ok(Collections.emptyList());
2347
        }
2348
    }
2349
 
2350
    @RequestMapping(value = "/indent/getOutOfStockDetails", method = RequestMethod.GET)
35782 ranu 2351
    public ResponseEntity<?> getOutOfStockDetails(HttpServletRequest request, @RequestParam String brand, @RequestParam int warehouseId, @RequestParam int fofoId, Model model) throws Exception {
35765 ranu 2352
        try {
2353
            // Get all catalogs for the brand with their movement status
2354
            List<CategorisedCatalogListModel> catalogMovements = categorisedCatalogRepository.getBrandWiseCatalogMovement(brand);
2355
 
2356
            // Filter only HID, FASTMOVING, RUNNING status
2357
            Set<CatalogMovingEnum> validStatuses = new HashSet<>(Arrays.asList(
2358
                    CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING));
2359
 
2360
            List<CategorisedCatalogListModel> filteredCatalogs = catalogMovements.stream()
2361
                    .filter(c -> validStatuses.contains(c.getCurrentStatus()))
2362
                    .collect(Collectors.toList());
2363
 
2364
            if (filteredCatalogs.isEmpty()) {
2365
                return responseSender.ok(Collections.emptyList());
2366
            }
2367
 
35782 ranu 2368
            // Get all catalog IDs for partner stock lookup
2369
            Set<Integer> allCatalogIds = filteredCatalogs.stream()
2370
                    .map(CategorisedCatalogListModel::getModelId)
2371
                    .collect(Collectors.toSet());
2372
 
2373
            // Get partner stock for all catalogs - fetch all partner stock and map to catalog IDs
2374
            Map<Integer, Integer> partnerStockMap = new HashMap<>();
2375
            if (!allCatalogIds.isEmpty()) {
2376
                List<CurrentInventorySnapshot> partnerSnapshots = currentInventorySnapshotRepository.selectByFofoId(fofoId);
2377
                // Get item IDs from snapshots
2378
                Set<Integer> itemIds = partnerSnapshots.stream()
2379
                        .map(CurrentInventorySnapshot::getItemId)
2380
                        .collect(Collectors.toSet());
2381
                // Get items to map itemId -> catalogId
2382
                Map<Integer, Integer> itemToCatalogMap = new HashMap<>();
2383
                for (Integer itemId : itemIds) {
2384
                    Item item = itemRepository.selectById(itemId);
2385
                    if (item != null) {
2386
                        itemToCatalogMap.put(itemId, item.getCatalogItemId());
2387
                    }
2388
                }
2389
                // Group by catalog ID
2390
                for (CurrentInventorySnapshot snap : partnerSnapshots) {
2391
                    Integer catalogId = itemToCatalogMap.get(snap.getItemId());
2392
                    if (catalogId != null && allCatalogIds.contains(catalogId)) {
2393
                        partnerStockMap.merge(catalogId, snap.getAvailability(), Integer::sum);
2394
                    }
2395
                }
2396
            }
2397
 
2398
            // Get GRN pending orders for partner
2399
            Map<Integer, Integer> grnPendingMap = new HashMap<>();
2400
            List<Order> pendingGrnOrders = orderRepository.selectPendingGrnOrders(fofoId);
2401
            for (Order order : pendingGrnOrders) {
2402
                int itemId = order.getLineItem().getItemId();
2403
                Item item = itemRepository.selectById(itemId);
2404
                if (item != null && allCatalogIds.contains(item.getCatalogItemId())) {
2405
                    grnPendingMap.merge(item.getCatalogItemId(), order.getLineItem().getQuantity(), Integer::sum);
2406
                }
2407
            }
2408
 
2409
            // Get tag listings (DP prices) for all catalogs
2410
            List<Integer> catalogIdList = new ArrayList<>(allCatalogIds);
2411
            Map<Integer, TagListing> tagListingsMap = tagListingRepository.selectAllByCatalogIds(catalogIdList);
2412
 
35765 ranu 2413
            List<Map<String, Object>> result = new ArrayList<>();
2414
 
2415
            for (CategorisedCatalogListModel catalogModel : filteredCatalogs) {
2416
                int catalogId = catalogModel.getModelId();
2417
 
2418
                // Get all items for this catalog
2419
                List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
2420
                List<Integer> itemIds = items.stream().map(Item::getId).collect(Collectors.toList());
2421
 
35782 ranu 2422
                // Get DP price from tag listings
2423
                TagListing tagListing = tagListingsMap.get(catalogId);
2424
                double dpPrice = tagListing != null ? tagListing.getSellingPrice() : 0;
2425
 
35765 ranu 2426
                if (itemIds.isEmpty()) {
2427
                    // No items means out of stock for this model
2428
                    Map<String, Object> itemDetail = new HashMap<>();
2429
                    itemDetail.put("catalogId", catalogId);
2430
                    itemDetail.put("modelNumber", catalogModel.getModelNumber());
2431
                    itemDetail.put("status", catalogModel.getCurrentStatus().getValue());
2432
                    itemDetail.put("qty", 0);
35782 ranu 2433
                    itemDetail.put("partnerCurrentQty", partnerStockMap.getOrDefault(catalogId, 0) + grnPendingMap.getOrDefault(catalogId, 0));
2434
                    itemDetail.put("dp", dpPrice);
35765 ranu 2435
                    result.add(itemDetail);
2436
                    continue;
2437
                }
2438
 
2439
                // Get saholic stock for these items
2440
                Map<Integer, List<WarehouseItemQtyModel>> stockMap = saholicInventoryService.getSaholicStock(warehouseId, itemIds);
2441
 
2442
                // Calculate total net availability for this catalog
2443
                int totalNetAvailability = 0;
2444
                for (Item item : items) {
2445
                    List<WarehouseItemQtyModel> stockList = stockMap.get(item.getId());
2446
                    if (stockList != null && !stockList.isEmpty()) {
2447
                        totalNetAvailability += stockList.stream()
2448
                                .mapToInt(WarehouseItemQtyModel::getNetAvailability)
2449
                                .sum();
2450
                    }
2451
                }
2452
 
2453
                // Only include if out of stock (netAvailability <= 0)
2454
                if (totalNetAvailability <= 0) {
2455
                    Map<String, Object> itemDetail = new HashMap<>();
2456
                    itemDetail.put("catalogId", catalogId);
2457
                    itemDetail.put("modelNumber", catalogModel.getModelNumber());
2458
                    itemDetail.put("status", catalogModel.getCurrentStatus().getValue());
2459
                    itemDetail.put("qty", totalNetAvailability);
35782 ranu 2460
                    itemDetail.put("partnerCurrentQty", partnerStockMap.getOrDefault(catalogId, 0) + grnPendingMap.getOrDefault(catalogId, 0));
2461
                    itemDetail.put("dp", dpPrice);
35765 ranu 2462
                    result.add(itemDetail);
2463
                }
2464
            }
2465
 
2466
            return responseSender.ok(result);
2467
        } catch (Exception e) {
35782 ranu 2468
            LOGGER.error("Error getting out of stock details for brand: {} warehouseId: {} fofoId: {}", brand, warehouseId, fofoId, e);
35765 ranu 2469
            return responseSender.ok(Collections.emptyList());
2470
        }
2471
    }
2472
 
34580 ranu 2473
    @Autowired
2474
    FofoOpeningStockRepository fofoOpeningStockRepository;
34449 ranu 2475
 
34087 ranu 2476
    @RequestMapping(value = "/getPartnerShortageStock", method = RequestMethod.GET)
2477
    public String getPartnerShortageStock(HttpServletRequest request,
35011 ranu 2478
                                          @RequestParam(required = false, defaultValue = "") String brand, @RequestParam(required = false, defaultValue = "0") long shortInvest, @RequestParam(required = false, defaultValue = "0") long totalDueWithInterest, @RequestParam int fofoId, Model model)
34087 ranu 2479
            throws Exception {
2480
 
34384 ranu 2481
        LocalDateTime presentDate = LocalDateTime.now();
34397 ranu 2482
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
34384 ranu 2483
 
34035 ranu 2484
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
34087 ranu 2485
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
34035 ranu 2486
 
34581 ranu 2487
        int warehouseId = fofoStore.getWarehouseId();
2488
 
34389 ranu 2489
        List<BrandWisePartnerSaleModel> brandWisePartnerSaleModels = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(Arrays.asList(fofoId));
2490
        LOGGER.info("brandWisePartnerSaleModels {}", brandWisePartnerSaleModels);
2491
 
2492
        Map<String, Long> brandToMtdMap = brandWisePartnerSaleModels.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getMtd()));
2493
 
34397 ranu 2494
        Map<Integer, Double> secondaryMtd = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
2495
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
2496
                curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
2497
 
2498
        double purchaseMtd = secondaryMtd.getOrDefault(fofoId, 0.0);
2499
 
2500
        Map<Integer, Double> secondaryToday = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
2501
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
2502
                curDate, curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
2503
 
2504
        double purchasedFtd = secondaryToday.getOrDefault(fofoId, 0.0);
2505
 
34412 ranu 2506
        MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
2507
 
34642 ranu 2508
        double purchaseTargetFtd = rbmTargetService.calculateFofoIdTodayTarget(fofoId, purchaseMtd, LocalDate.now());
34397 ranu 2509
 
2510
        double saleMtd = (Double) fofoUser.getSales(fofoId).get("mtdSale");
2511
 
2512
        double recoverableAmount = saleMtd - purchaseMtd;
2513
 
2514
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
34412 ranu 2515
 
34397 ranu 2516
        UserWallet userWallet = walletService.getUserWallet(fofoId);
2517
 
34412 ranu 2518
        BigDecimal totalAvailableFunds = sdCreditRequirement.getAvailableLimit().add(BigDecimal.valueOf(userWallet.getAmount()));
34397 ranu 2519
 
2520
        List<Loan> loans = loanRepository.selectActiveLoan(fofoId);
34412 ranu 2521
        double totalPendingAmount = loans.stream()
2522
                .map(Loan::getPendingAmount)
2523
                .mapToDouble(BigDecimal::doubleValue)
2524
                .sum();
2525
 
34397 ranu 2526
        boolean isLoanPending = false;
2527
        if (loans.size() > 0) {
2528
            isLoanPending = true;
2529
        }
2530
 
34389 ranu 2531
 
34035 ranu 2532
        List<PartnerWarehouseStockSummaryModel> partnerWarehouseStockSummaryModels = saholicInventoryService.getSaholicAndPartnerStock(fofoId, fofoStore.getWarehouseId());
2533
 
34569 ranu 2534
        List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == fofoStore.getWarehouseId())).collect(Collectors.toList());
2535
 
34589 ranu 2536
        Map<Integer, Long> catalogWiseQtyMap = new HashMap<>();
2537
        Set<Integer> inTransitCatalogIds = new HashSet<>();
2538
        List<PartnerWarehouseStockSummaryModel> intransistSummaryList = new ArrayList<>();
2539
        if (warehouseIntransitDataModels.size() > 0) {
2540
            Map<Integer, List<WarehouseIntransitDataModel>> warewarehouseIntransitDataModelsMap = warehouseIntransitDataModels.stream().collect(Collectors.groupingBy(WarehouseIntransitDataModel::getCatalogId));
34580 ranu 2541
 
34589 ranu 2542
            catalogWiseQtyMap = warehouseIntransitDataModels.stream()
2543
                    .collect(Collectors.groupingBy(
2544
                            WarehouseIntransitDataModel::getCatalogId,
2545
                            Collectors.summingLong(WarehouseIntransitDataModel::getQty)
2546
                    ));
34569 ranu 2547
 
34589 ranu 2548
            LOGGER.info("catalogWiseQtyMap key set {}", catalogWiseQtyMap.keySet());
34035 ranu 2549
 
34589 ranu 2550
            List<FofoOpeningStock> fofoOpeningStocksLitsForIntransist = fofoOpeningStockRepository.fofoOpeningStockByFofoId(catalogWiseQtyMap.keySet(), fofoId);
2551
            LOGGER.info("fofoOpeningStocksLitsForIntransist {}", fofoOpeningStocksLitsForIntransist);
2552
            // Optional: Build a map for faster lookup
2553
            Map<Integer, FofoOpeningStock> inTransistfofoOpeningStockMap = fofoOpeningStocksLitsForIntransist.stream()
2554
                    .collect(Collectors.toMap(FofoOpeningStock::getCatalogId, stock -> stock));
34437 ranu 2555
 
2556
 
34589 ranu 2557
            for (Map.Entry<Integer, Long> entry : catalogWiseQtyMap.entrySet()) {
2558
                int catalogId = entry.getKey();
2559
                long netAvailability = entry.getValue();
34580 ranu 2560
 
34589 ranu 2561
                FofoOpeningStock openingStock = inTransistfofoOpeningStockMap.get(catalogId);
2562
                WarehouseIntransitDataModel warehouseIntransitDataModel = warewarehouseIntransitDataModelsMap.get(catalogId).get(0);
34580 ranu 2563
 
34589 ranu 2564
                PartnerWarehouseStockSummaryModel inTransistmodel = new PartnerWarehouseStockSummaryModel(
2565
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getBrand() : "Unknown",
2566
                        catalogId,
2567
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getItemDescription() : "Unknown",
2568
                        warehouseIntransitDataModel != null ? 10006 : 0,
2569
                        (int) netAvailability,
2570
                        openingStock != null ? openingStock.getOpeningQty() : 0,
2571
                        openingStock != null ? openingStock.getCurrentQty() : 0,
2572
                        openingStock != null ? (openingStock.getOpeningQty() - openingStock.getCurrentQty()) : 0,
2573
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getStatus() : "Unknown"
2574
                );
34580 ranu 2575
 
34589 ranu 2576
                intransistSummaryList.add(inTransistmodel);
2577
            }
34580 ranu 2578
        }
2579
 
34589 ranu 2580
 
34490 ranu 2581
        List<DateWiseSoldCatalogQtyModel> sevenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(7));
34384 ranu 2582
 
34490 ranu 2583
        List<DateWiseSoldCatalogQtyModel> fourteenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(14));
34384 ranu 2584
 
34490 ranu 2585
        List<DateWiseSoldCatalogQtyModel> twentyOneDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(21));
34412 ranu 2586
 
34384 ranu 2587
        LOGGER.info("twentyOneDayAboveSoldsCatalogs {}", twentyOneDayAboveSoldsCatalogs);
34412 ranu 2588
 
34490 ranu 2589
        List<DateWiseSoldCatalogQtyModel> twentyEightDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(28));
34384 ranu 2590
 
34580 ranu 2591
        Set<Integer> catalogIds = partnerWarehouseStockSummaryModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
34412 ranu 2592
 
34589 ranu 2593
        if (!catalogWiseQtyMap.isEmpty()) {
2594
            inTransitCatalogIds = catalogWiseQtyMap.keySet().stream().filter(catalogId -> !catalogIds.contains(catalogId)).collect(Collectors.toSet());
2595
        }
34580 ranu 2596
 
2597
        // Add the missing IDs to the original set
2598
        catalogIds.addAll(inTransitCatalogIds);
2599
 
2600
        List<Integer> catalogsList = new ArrayList<>(catalogIds);
2601
 
2602
        Map<Integer, TagListing> tagListingsMap = tagListingRepository.selectAllByCatalogIds(catalogsList);
2603
 
34035 ranu 2604
        List<CatalogAgingModel> catalogAgingModels = ageingService.getCatalogsAgingByWarehouse(catalogIds, fofoStore.getWarehouseId());
2605
 
2606
        Map<Integer, CatalogAgingModel> catalogAgingModelMap = catalogAgingModels.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
2607
 
2608
        List<PartnerWarehouseStockAgingSummaryModel> partnerWarehouseStockAgingSummaryModelList = new ArrayList<>();
2609
 
2610
        for (PartnerWarehouseStockSummaryModel stockSummary : partnerWarehouseStockSummaryModels) {
2611
 
2612
            PartnerWarehouseStockAgingSummaryModel partnerWarehouseStockAgingSummaryModel = new PartnerWarehouseStockAgingSummaryModel();
2613
            partnerWarehouseStockAgingSummaryModel.setCatalogId(stockSummary.getCatalogId());
2614
            partnerWarehouseStockAgingSummaryModel.setBrand(stockSummary.getBrand());
2615
            partnerWarehouseStockAgingSummaryModel.setModelNumber(stockSummary.getModelNumber());
2616
            partnerWarehouseStockAgingSummaryModel.setNetAvailability(stockSummary.getShaholicNetAvailability());
2617
            partnerWarehouseStockAgingSummaryModel.setPartnerStockAvailability(stockSummary.getPartnerFullFilledQty());
2618
            partnerWarehouseStockAgingSummaryModel.setPartnerCurrentAvailability(stockSummary.getPartnerCurrentQty());
2619
            partnerWarehouseStockAgingSummaryModel.setPartnerShortageStock(stockSummary.getPartnerShortageQty());
34472 ranu 2620
            if (catalogAgingModelMap.get(stockSummary.getCatalogId()) != null) {
2621
                partnerWarehouseStockAgingSummaryModel.setExceedDays(catalogAgingModelMap.get(stockSummary.getCatalogId()).getExceedDays());
34489 ranu 2622
            } else {
2623
                partnerWarehouseStockAgingSummaryModel.setExceedDays(0);
2624
 
34472 ranu 2625
            }
34035 ranu 2626
            partnerWarehouseStockAgingSummaryModel.setStatus(stockSummary.getStatus());
2627
 
2628
            partnerWarehouseStockAgingSummaryModelList.add(partnerWarehouseStockAgingSummaryModel);
2629
        }
2630
 
34580 ranu 2631
        Set<Integer> existingCatalogIdsInAgingSummaryList = partnerWarehouseStockAgingSummaryModelList.stream()
2632
                .map(PartnerWarehouseStockAgingSummaryModel::getCatalogId)
2633
                .collect(Collectors.toSet());
34389 ranu 2634
 
34589 ranu 2635
        if (intransistSummaryList.size() > 0) {
2636
            // Step 2: Iterate over intransitSummaryList and add missing ones
2637
            for (PartnerWarehouseStockSummaryModel intransitStock : intransistSummaryList) {
2638
                if (!existingCatalogIdsInAgingSummaryList.contains(intransitStock.getCatalogId())) {
2639
                    PartnerWarehouseStockAgingSummaryModel agingModel = new PartnerWarehouseStockAgingSummaryModel();
2640
                    agingModel.setCatalogId(intransitStock.getCatalogId());
2641
                    agingModel.setBrand(intransitStock.getBrand());
2642
                    agingModel.setModelNumber(intransitStock.getModelNumber());
2643
                    agingModel.setNetAvailability(0); // Not part of original aging summary
2644
                    agingModel.setPartnerStockAvailability(intransitStock.getPartnerFullFilledQty());
2645
                    agingModel.setPartnerCurrentAvailability(intransitStock.getPartnerCurrentQty());
2646
                    agingModel.setPartnerShortageStock(intransitStock.getPartnerShortageQty());
2647
                    if (catalogAgingModelMap.get(intransitStock.getCatalogId()) != null) {
2648
                        agingModel.setExceedDays(catalogAgingModelMap.get(intransitStock.getCatalogId()).getExceedDays());
2649
                    } else {
2650
                        agingModel.setExceedDays(0);
2651
                    }
2652
                    agingModel.setStatus(intransitStock.getStatus() == null ? "OTHER" : intransitStock.getStatus());
2653
 
2654
                    partnerWarehouseStockAgingSummaryModelList.add(agingModel);
34580 ranu 2655
                }
2656
            }
2657
        }
2658
 
2659
 
34384 ranu 2660
        List<String> statusOrder = Arrays.asList("HID", "FASTMOVING", "RUNNING", "SLOWMOVING", "OTHER");
34035 ranu 2661
 
2662
        Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> brandStatusWiseStockListMap =
2663
                partnerWarehouseStockAgingSummaryModelList.stream().collect(Collectors.groupingBy(
2664
                        PartnerWarehouseStockAgingSummaryModel::getBrand,
2665
                        Collectors.groupingBy(PartnerWarehouseStockAgingSummaryModel::getStatus)
2666
                ));
34389 ranu 2667
//map of list as hid,fast,slow and other in last otherwise other is coming in start (here is using status order)
35782 ranu 2668
        // Also sort items alphabetically by model number within each status group
34035 ranu 2669
        Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> sortedBrandStatusWiseStockListMap =
2670
                brandStatusWiseStockListMap.entrySet().stream().collect(Collectors.toMap(
2671
                        Map.Entry::getKey, // Key (Brand)
2672
                        entry -> {
2673
                            Map<String, List<PartnerWarehouseStockAgingSummaryModel>> sortedStatusMap = entry.getValue().entrySet().stream()
2674
                                    .sorted((e1, e2) -> Integer.compare(
2675
                                            statusOrder.indexOf(e1.getKey()),
2676
                                            statusOrder.indexOf(e2.getKey())
2677
                                    ))
2678
                                    .collect(Collectors.toMap(
2679
                                            Map.Entry::getKey,
35782 ranu 2680
                                            e -> e.getValue().stream()
2681
                                                    .sorted(Comparator.comparing(PartnerWarehouseStockAgingSummaryModel::getModelNumber, String.CASE_INSENSITIVE_ORDER))
2682
                                                    .collect(Collectors.toList()),
34035 ranu 2683
                                            (v1, v2) -> v1,
2684
                                            LinkedHashMap::new // Ensure ordering is maintained
2685
                                    ));
2686
                            return sortedStatusMap;
2687
                        },
2688
                        (v1, v2) -> v1,
2689
                        LinkedHashMap::new // Maintain order of brands
2690
                ));
34490 ranu 2691
        LOGGER.info("brandToMtdMap {}", brandToMtdMap);
34454 ranu 2692
        List<String> sortedBrandsByMtd = brandToMtdMap.entrySet()
2693
                .stream()
2694
                .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // Descending MTD
2695
                .map(Map.Entry::getKey)
2696
                .collect(Collectors.toList());
2697
 
2698
        List<String> remainingBrands = ProfitMandiConstants.BRANDS.stream()
2699
                .filter(x -> !brandToMtdMap.containsKey(x))
2700
                .filter(x -> sortedBrandStatusWiseStockListMap.containsKey(x))
2701
                .collect(Collectors.toList());
2702
        List<String> remainingBrandsWithoutStock = ProfitMandiConstants.BRANDS.stream()
2703
                .filter(x -> !brandToMtdMap.containsKey(x))
2704
                .filter(x -> !sortedBrandStatusWiseStockListMap.containsKey(x)) // no stock
2705
                .collect(Collectors.toList());
2706
 
34683 ranu 2707
        List<InStockBrandItemModel> inStockBrandItemModels = currentInventorySnapshotRepository.selectInStockItemsByBrand(fofoId);
2708
 
2709
        Map<String, Long> brandsWithPartnerStockMap = inStockBrandItemModels.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand, Collectors.summingLong(InStockBrandItemModel::getQty)));
2710
        List<String> brandsWithPartnerStock = brandsWithPartnerStockMap.entrySet().stream().filter(x -> x.getValue() > 0).map(x -> x.getKey()).collect(Collectors.toList());
34513 ranu 2711
        List<String> sortedBrands = new ArrayList<>();
2712
        sortedBrands.addAll(sortedBrandsByMtd);
2713
        sortedBrands.addAll(remainingBrands);
2714
        sortedBrands.addAll(remainingBrandsWithoutStock);
34454 ranu 2715
 
34513 ranu 2716
        List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
2717
 
2718
        List<String> finalSortedBrands = sortedBrands.stream().filter(x -> !partnerIneligibleBrands.contains(x) && !"itel".equalsIgnoreCase(x)).collect(Collectors.toList());
2719
 
34487 ranu 2720
        Map<Integer, Integer> processingOrderMap = null;
2721
        List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();
2722
        Map<Integer, PartnerStockDetailModel> pendingIndentsDetailMap = new HashMap<>();
2723
 
2724
        Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
2725
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2726
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2727
        if (!processingOrder.isEmpty()) {
2728
            processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
2729
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2730
                            Collectors.summingInt(x -> processingOrder.get(x.getId()))));
2731
            pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));
2732
            pendingIndentsDetailMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
2733
 
2734
        }
2735
        LOGGER.info("pendingIndents {}", pendingIndents);
2736
        LOGGER.info("pendingIndentsDetailMap {}", pendingIndentsDetailMap);
2737
 
34035 ranu 2738
        model.addAttribute("brandStatusWiseStockListMap", sortedBrandStatusWiseStockListMap);
34683 ranu 2739
        model.addAttribute("brandsWithPartnerStock", brandsWithPartnerStock);
34487 ranu 2740
        model.addAttribute("pendingIndentsDetailMap", pendingIndentsDetailMap);
34412 ranu 2741
        model.addAttribute("brands", finalSortedBrands);
2742
        model.addAttribute("brandToMtdMap", brandToMtdMap);
34569 ranu 2743
        model.addAttribute("catalogWiseQtyMap", catalogWiseQtyMap);
34580 ranu 2744
        model.addAttribute("intransistSummaryList", intransistSummaryList);
34087 ranu 2745
        model.addAttribute("brand", brand);
2746
        model.addAttribute("fofoId", fofoId);
34581 ranu 2747
        model.addAttribute("warehouseId", warehouseId);
34087 ranu 2748
        model.addAttribute("customRetailer", customRetailer);
34397 ranu 2749
        model.addAttribute("shortInvest", shortInvest);
35011 ranu 2750
        model.addAttribute("totalDueWithInterest", totalDueWithInterest);
35771 ranu 2751
        model.addAttribute("interestDue", Math.subtractExact(totalDueWithInterest, sdCreditRequirement.getUtilizedAmount().intValue()));
2752
 
34397 ranu 2753
        model.addAttribute("purchaseMtd", purchaseMtd);
2754
        model.addAttribute("purchasedFtd", purchasedFtd);
2755
        model.addAttribute("saleMtd", saleMtd);
2756
        model.addAttribute("purchaseTargetFtd", purchaseTargetFtd);
2757
        model.addAttribute("recoverableAmount", recoverableAmount);
2758
        model.addAttribute("isLoanPending", isLoanPending);
2759
        model.addAttribute("totalAvailableFunds", totalAvailableFunds);
34412 ranu 2760
        model.addAttribute("sdCreditRequirement", sdCreditRequirement);
2761
        model.addAttribute("userWallet", userWallet);
2762
        model.addAttribute("monthlyTarget", monthlyTarget);
2763
        model.addAttribute("totalPendingAmount", totalPendingAmount);
34437 ranu 2764
        model.addAttribute("tagListingsMap", tagListingsMap);
34412 ranu 2765
        model.addAttribute("sevenDayAboveSoldsCatalogs", sevenDayAboveSoldsCatalogs);
2766
        model.addAttribute("fourteenDayAboveSoldsCatalogs", fourteenDayAboveSoldsCatalogs);
2767
        model.addAttribute("twentyOneDayAboveSoldsCatalogs", twentyOneDayAboveSoldsCatalogs);
2768
        model.addAttribute("twentyEightDayAboveSoldsCatalogs", twentyEightDayAboveSoldsCatalogs);
32839 amit.gupta 2769
        return "partner-stock";
30003 tejbeer 2770
 
32839 amit.gupta 2771
    }
30044 tejbeer 2772
 
32839 amit.gupta 2773
    private List<PartnerStockDescriptionModel> getBrandItemwiseDescription(String brand,
2774
                                                                           Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
2775
        List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();
30044 tejbeer 2776
 
32839 amit.gupta 2777
        for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2778
            List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
30044 tejbeer 2779
 
32839 amit.gupta 2780
            if (brand.equals("accessories")) {
2781
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
30044 tejbeer 2782
 
32839 amit.gupta 2783
                    if (items.get(0).getCategoryId() != 0) {
2784
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30044 tejbeer 2785
 
32839 amit.gupta 2786
                        if (category.getParentCategoryId() == 10011) {
2787
                            PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2788
                            psdp.setBrand(items.get(0).getBrand());
2789
                            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2790
                                    + items.get(0).getModelNumber());
2791
                            psdp.setQty(inStock.getValue());
2792
                            inStocks.add(psdp);
2793
                        }
2794
                    }
30044 tejbeer 2795
 
32839 amit.gupta 2796
                }
30044 tejbeer 2797
 
32839 amit.gupta 2798
            } else if (brand.equals("TV")) {
2799
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
30044 tejbeer 2800
 
32839 amit.gupta 2801
                    if (items.get(0).getCategoryId() != 0) {
2802
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30044 tejbeer 2803
 
32839 amit.gupta 2804
                        if (category.getParentCategoryId() == 14200) {
2805
                            PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2806
                            psdp.setBrand(items.get(0).getBrand());
2807
                            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2808
                                    + items.get(0).getModelNumber());
2809
                            psdp.setQty(inStock.getValue());
2810
                            inStocks.add(psdp);
2811
                        }
2812
                    }
30044 tejbeer 2813
 
32839 amit.gupta 2814
                }
30044 tejbeer 2815
 
32839 amit.gupta 2816
            } else {
2817
                PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2818
                psdp.setBrand(items.get(0).getBrand());
2819
                psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2820
                        + items.get(0).getModelNumber());
2821
                psdp.setQty(inStock.getValue());
2822
                inStocks.add(psdp);
2823
            }
30044 tejbeer 2824
 
32839 amit.gupta 2825
        }
30044 tejbeer 2826
 
32839 amit.gupta 2827
        return inStocks;
2828
    }
30003 tejbeer 2829
 
34487 ranu 2830
    private List<PartnerStockDetailModel> getBrandItemwiseDetail(String brand,
2831
                                                                 Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
2832
        List<PartnerStockDetailModel> inStocks = new ArrayList<>();
2833
 
2834
        for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2835
            List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
2836
            PartnerStockDetailModel psdp = new PartnerStockDetailModel();
2837
            psdp.setBrand(items.get(0).getBrand());
2838
            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2839
                    + items.get(0).getModelNumber());
2840
            psdp.setQty(inStock.getValue());
2841
            psdp.setCatalogId(items.get(0).getCatalogItemId());
2842
            inStocks.add(psdp);
2843
        }
2844
 
2845
        return inStocks;
2846
    }
2847
 
32839 amit.gupta 2848
    private FocusedModelShortageModel getFocusedModelShortage(int qty, int catalogId,
2849
                                                              Map<Integer, Integer> processingOrderMap, Map<Integer, Integer> grnPendingOrdersMap,
2850
                                                              Map<Integer, Integer> catalogIdAndQtyMap, int fofoId,
2851
                                                              Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap, List<Item> items,
2852
                                                              CustomRetailer customRetailer) throws ProfitMandiBusinessException {
30003 tejbeer 2853
 
32839 amit.gupta 2854
        int minQty = qty;
2855
        int inStockQty = 0;
2856
        int processingQty = 0;
2857
        int grnPendingQty = 0;
2858
        int allColorNetAvailability = 0;
2859
        int allColorPoAvailability = 0;
2860
        if (processingOrderMap != null) {
2861
            processingQty = (processingOrderMap.get(catalogId) == null) ? 0 : processingOrderMap.get(catalogId);
30003 tejbeer 2862
 
32839 amit.gupta 2863
        }
2864
        if (grnPendingOrdersMap != null) {
2865
            grnPendingQty = (grnPendingOrdersMap.get(catalogId) == null) ? 0 : grnPendingOrdersMap.get(catalogId);
30003 tejbeer 2866
 
32839 amit.gupta 2867
        }
2868
        if (catalogIdAndQtyMap != null) {
2869
            inStockQty = (catalogIdAndQtyMap.get(catalogId) == null) ? 0 : catalogIdAndQtyMap.get(catalogId);
30003 tejbeer 2870
 
32839 amit.gupta 2871
        }
30003 tejbeer 2872
 
32839 amit.gupta 2873
        int grnStockQty = grnPendingQty + inStockQty;
2874
        int totalQty = processingQty + grnPendingQty + inStockQty;
30003 tejbeer 2875
 
32839 amit.gupta 2876
        int shortageQty = minQty - totalQty;
2877
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
30003 tejbeer 2878
 
32839 amit.gupta 2879
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap
2880
                .get(fofoStore.getWarehouseId());
30003 tejbeer 2881
 
32839 amit.gupta 2882
        for (Item it : items) {
2883
            List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(it.getId(),
2884
                    fofoStore.getWarehouseId());
2885
            List<SaholicPOItem> poItemAvailability = null;
30003 tejbeer 2886
 
32839 amit.gupta 2887
            if (poItemAvailabilityMap != null) {
2888
                poItemAvailability = poItemAvailabilityMap.get(it.getId());
2889
            }
2890
            if (currentAvailability != null) {
2891
                allColorNetAvailability += currentAvailability.stream()
2892
                        .collect(Collectors.summingInt(SaholicCISTable::getNetAvailability));
2893
            }
30003 tejbeer 2894
 
32839 amit.gupta 2895
            if (poItemAvailability != null) {
2896
                allColorPoAvailability += poItemAvailability.stream()
2897
                        .collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
2898
            }
30003 tejbeer 2899
 
32839 amit.gupta 2900
        }
30003 tejbeer 2901
 
32839 amit.gupta 2902
        FocusedModelShortageModel fm = new FocusedModelShortageModel();
2903
        fm.setFofoId(fofoId);
2904
        fm.setStoreCode(fofoStore.getCode());
2905
        fm.setStoreName(customRetailer.getBusinessName());
2906
        fm.setBrandName(items.get(0).getBrand());
2907
        fm.setModelName(items.get(0).getModelName());
2908
        fm.setModelNumber(items.get(0).getModelNumber());
2909
        fm.setGrnStockQty(grnStockQty);
2910
        fm.setPendingIndentQty(processingQty);
2911
        fm.setShortageQty(shortageQty);
2912
        fm.setPoAvailability(allColorPoAvailability);
2913
        fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
2914
        fm.setAvailability(allColorNetAvailability);
2915
        return fm;
30003 tejbeer 2916
 
32839 amit.gupta 2917
    }
30017 amit.gupta 2918
 
32839 amit.gupta 2919
    @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.GET)
2920
    public String SendPONotification(HttpServletRequest request, Model model) {
2921
        model.addAttribute("warehouses", ProfitMandiConstants.WAREHOUSE_MAP);
2922
        return "send-po-notification";
2923
    }
30017 amit.gupta 2924
 
32839 amit.gupta 2925
    @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.POST)
2926
    public String sendPONotification(HttpServletRequest request, @RequestBody POItemWarehouseModel poItemWarehouseModel,
2927
                                     Model model) throws Exception {
30017 amit.gupta 2928
 
32839 amit.gupta 2929
        Map<Integer, Item> selectedCatalogItemMap = itemRepository
2930
                .selectAllByCatalogIds(new HashSet<>(poItemWarehouseModel.getCatalogIds())).stream()
2931
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x, (existing, replacement) -> existing));
30080 amit.gupta 2932
 
32839 amit.gupta 2933
        Set<String> brands = selectedCatalogItemMap.values().stream().map(x -> x.getBrand().toLowerCase())
2934
                .collect(Collectors.toSet());
30017 amit.gupta 2935
 
32839 amit.gupta 2936
        int warehouseId = poItemWarehouseModel.getWarehouseId();
2937
        for (String brand : brands) {
2938
            List<String> modelNames = selectedCatalogItemMap.entrySet().stream()
2939
                    .filter(x -> x.getValue().getBrand().toLowerCase().equals(brand))
2940
                    .map(x -> x.getValue().getItemDescriptionNoColor()).collect(Collectors.toList());
2941
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
2942
            sendNotificationModel.setCampaignName("SendPo");
2943
            sendNotificationModel.setTitle(String.format(PO_TITLE_STRING));
2944
            sendNotificationModel.setMessage(String.join(", ", modelNames));
2945
            sendNotificationModel.setType("url");
2946
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
2947
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2948
            sendNotificationModel.setMessageType(MessageType.notification);
30017 amit.gupta 2949
 
32839 amit.gupta 2950
            List<BrandRegionMapping> brandRegionMappings = brandRegionMappingRepository.selectAll().stream()
2951
                    .filter(x -> brand.equals(x.getBrand().toLowerCase()) && x.getFromWarehouseId() == warehouseId
2952
                            && !x.isAccessory())
2953
                    .collect(Collectors.toList());
2954
            List<Integer> toWarehouseIds = brandRegionMappings.stream().map(x -> x.getToWarehouseId())
2955
                    .collect(Collectors.toList());
30017 amit.gupta 2956
 
32839 amit.gupta 2957
            List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(toWarehouseIds).stream()
2958
                    .filter(x -> !x.isInternal() && x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
30017 amit.gupta 2959
 
32839 amit.gupta 2960
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
2961
            sendNotificationModel.setUserIds(userIds);
2962
            notificationService.sendNotification(sendNotificationModel);
2963
        }
2964
        model.addAttribute("response1", true);
2965
        return "response";
2966
    }
2967
 
25721 tejbeer 2968
}