Subversion Repositories SmartDukaan

Rev

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