Subversion Repositories SmartDukaan

Rev

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