Subversion Repositories SmartDukaan

Rev

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