Subversion Repositories SmartDukaan

Rev

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