Subversion Repositories SmartDukaan

Rev

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