Subversion Repositories SmartDukaan

Rev

Rev 35765 | Rev 35776 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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