Subversion Repositories SmartDukaan

Rev

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

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