Subversion Repositories SmartDukaan

Rev

Rev 35782 | Details | Compare with Previous | Last modification | View Log | RSS feed

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