Subversion Repositories SmartDukaan

Rev

Rev 35484 | Rev 35547 | 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<>();
35490 ranu 1726
 
1727
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> inStockQtyAccessTv = new HashMap<>();
1728
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> pendingIndentQtyAccessTv = new HashMap<>();
1729
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> grnPendingQtyAccessTvOrders = new HashMap<>();
32839 amit.gupta 1730
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1731
        Map<Integer, CustomRetailer> customRetailers = new HashMap<>();
1732
        Map<Integer, PartnerType> fofoIdPartnerTypeMap = new HashMap<>();
30003 tejbeer 1733
 
32839 amit.gupta 1734
        if (fofoIds != null && fofoIds.size() > 0) {
1735
            List<Integer> fofoIdList = new ArrayList<>(fofoIds);
30003 tejbeer 1736
 
32839 amit.gupta 1737
            Map<Integer, ActivationType> partnerActivationType = fofoStoreRepository.selectByRetailerIds(fofoIdList)
1738
                    .stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getActivationType()));
1739
            //Only L3 and above can change the accessType
35395 amit 1740
            boolean canChangeActionType = positionRepository.selectAllByAuthUserId(authUser.getId())
32839 amit.gupta 1741
                    .stream().filter(x -> x.getEscalationType().isGreaterThanEqualTo(EscalationType.L3)).count() > 0;
1742
            model.addAttribute("canChangeActivationType", canChangeActionType);
1743
            model.addAttribute("partnerActivationType", partnerActivationType);
1744
            model.addAttribute("activationTypes", ActivationType.values());
30046 tejbeer 1745
 
32839 amit.gupta 1746
            Map<Integer, FofoReportingModel> partnerSalesHeadersMap = csService.getPartnerIdSalesHeaders();
30046 tejbeer 1747
 
32839 amit.gupta 1748
            model.addAttribute("partnerSalesHeadersMap", partnerSalesHeadersMap);
30003 tejbeer 1749
 
32839 amit.gupta 1750
            Map<Integer, Map<String, Float>> partnerBrandLimitMap = brandLimitRepository.selectAllPartnerBrandLimit()
1751
                    .stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1752
                            Collectors.toMap(x -> x.getBrand(), x -> x.getBrandLimit())));
30044 tejbeer 1753
 
32839 amit.gupta 1754
            model.addAttribute("partnerBrandLimitMap", partnerBrandLimitMap);
1755
            customRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1756
                    .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1757
            Map<Integer, Map<String, Double>> inStockBrandModel;
35484 ranu 1758
            Map<Integer, Map<String, Double>> inStockBrandModelQty;
32839 amit.gupta 1759
            Map<Integer, Map<String, Double>> pendingIndent;
35484 ranu 1760
            Map<Integer, Map<String, Double>> pendingIndentQty;
32839 amit.gupta 1761
            Map<Integer, Map<String, Double>> grnPendingOrders;
35484 ranu 1762
            Map<Integer, Map<String, Double>> grnPendingOrdersQty;
30044 tejbeer 1763
 
32839 amit.gupta 1764
            // mobile
35490 ranu 1765
            List<InStockBrandFofoIdModel> inStockBrandFofoIdModels = currentInventorySnapshotRepository.selectSumInStockMobiletabletGroupByBrand(fofoIdList);
1766
 
1767
            inStockBrandModel = inStockBrandFofoIdModels
32839 amit.gupta 1768
                    .stream()
1769
                    .collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1770
                            Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1771
                                    Collectors.summingDouble(InStockBrandFofoIdModel::getAmount))));
30003 tejbeer 1772
 
35490 ranu 1773
            inStockBrandModelQty = inStockBrandFofoIdModels
35484 ranu 1774
                    .stream()
1775
                    .collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1776
                            Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1777
                                    Collectors.summingDouble(InStockBrandFofoIdModel::getQty))));
1778
 
35490 ranu 1779
            List<Order> pendingIndentOrders = transactionService.getInTransitOrders(fofoIdList);
1780
 
1781
            pendingIndent = pendingIndentOrders.stream()
32839 amit.gupta 1782
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1783
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1784
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1785
                                    Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
30003 tejbeer 1786
 
35490 ranu 1787
 
1788
            pendingIndentQty = pendingIndentOrders.stream()
35484 ranu 1789
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1790
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1791
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1792
                                    Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));
1793
 
35490 ranu 1794
 
1795
            List<Order> grnPendingOrderList = orderRepository.selectPendingGrnOrders(fofoIdList);
1796
 
1797
            grnPendingOrders = grnPendingOrderList.stream()
32839 amit.gupta 1798
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1799
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1800
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1801
                                    Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
35490 ranu 1802
            grnPendingOrdersQty = grnPendingOrderList.stream()
35484 ranu 1803
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1804
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1805
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1806
                                    Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));
30003 tejbeer 1807
 
32839 amit.gupta 1808
            // accessories
1809
            inStockAccessTv = currentInventorySnapshotRepository.selectSumInStockAccessoriesAndTv(fofoIdList).stream()
1810
                    .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1811
 
32839 amit.gupta 1812
            pendingIndentAccessTv = orderRepository.selectAllPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1813
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1814
 
32839 amit.gupta 1815
            grnPendingAccessTvOrders = orderRepository.selectAllGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1816
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1817
 
35490 ranu 1818
 
1819
            inStockQtyAccessTv = currentInventorySnapshotRepository.selectQtySumInStockAccessoriesAndTv(fofoIdList).stream()
1820
                    .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1821
 
1822
            pendingIndentQtyAccessTv = orderRepository.selectAllQtyPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1823
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1824
 
1825
            grnPendingQtyAccessTvOrders = orderRepository.selectAllQtyGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1826
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1827
 
35462 amit 1828
            // Bulk fetch partner types to avoid N+1 queries
1829
            fofoIdPartnerTypeMap = partnerTypeChangeService.getTypesForFofoIds(new ArrayList<>(customRetailers.keySet()), LocalDate.now());
1830
 
32839 amit.gupta 1831
            for (Entry<Integer, CustomRetailer> customRetailer : customRetailers.entrySet()) {
1832
                Map<String, Double> stockBrand = inStockBrandModel.get(customRetailer.getKey());
35484 ranu 1833
                Map<String, Double> stockBrandQty = inStockBrandModelQty.get(customRetailer.getKey());
32839 amit.gupta 1834
                Map<String, Double> pendingIndentBrand = pendingIndent.get(customRetailer.getKey());
35484 ranu 1835
                Map<String, Double> pendingIndentBrandQty = pendingIndentQty.get(customRetailer.getKey());
32839 amit.gupta 1836
                Map<String, Double> grnBrand = grnPendingOrders.get(customRetailer.getKey());
35484 ranu 1837
                Map<String, Double> grnBrandQty = grnPendingOrdersQty.get(customRetailer.getKey());
32839 amit.gupta 1838
                double totalAmount = 0;
35484 ranu 1839
                double totalQty = 0;
30024 tejbeer 1840
 
32839 amit.gupta 1841
                Map<String, Double> brandAmountMap = new HashMap<>();
35484 ranu 1842
                Map<String, Double> brandQtyMap = new HashMap<>();
32839 amit.gupta 1843
                for (String brand : brands) {
30024 tejbeer 1844
 
32839 amit.gupta 1845
                    double stockValue = 0;
35484 ranu 1846
                    double stockQty = 0;
32839 amit.gupta 1847
                    double pendingValue = 0;
35484 ranu 1848
                    double pendingQty = 0;
32839 amit.gupta 1849
                    double grnValue = 0;
35484 ranu 1850
                    double grnQty = 0;
32839 amit.gupta 1851
                    if (stockBrand != null) {
30024 tejbeer 1852
 
32839 amit.gupta 1853
                        if (stockBrand.get(brand) != null) {
1854
                            stockValue = stockBrand.get(brand);
1855
                        }
1856
                    }
30024 tejbeer 1857
 
35484 ranu 1858
                    if (stockBrandQty != null) {
1859
 
1860
                        if (stockBrandQty.get(brand) != null) {
1861
                            stockQty = stockBrandQty.get(brand);
1862
                        }
1863
                    }
1864
 
32839 amit.gupta 1865
                    if (pendingIndentBrand != null) {
1866
                        if (pendingIndentBrand.get(brand) != null) {
1867
                            pendingValue = pendingIndentBrand.get(brand);
1868
                        }
1869
                    }
35484 ranu 1870
                    if (pendingIndentBrandQty != null) {
1871
                        if (pendingIndentBrandQty.get(brand) != null) {
1872
                            pendingQty = pendingIndentBrandQty.get(brand);
1873
                        }
1874
                    }
30024 tejbeer 1875
 
32839 amit.gupta 1876
                    if (grnBrand != null) {
1877
                        if (grnBrand.get(brand) != null) {
1878
                            grnValue = grnBrand.get(brand);
1879
                        }
1880
                    }
30024 tejbeer 1881
 
35484 ranu 1882
                    if (grnBrandQty != null) {
1883
                        if (grnBrandQty.get(brand) != null) {
1884
                            grnQty = grnBrandQty.get(brand);
1885
                        }
1886
                    }
1887
 
32839 amit.gupta 1888
                    totalAmount = stockValue + pendingValue + grnValue;
30024 tejbeer 1889
 
35484 ranu 1890
                    totalQty = stockQty + pendingQty + grnQty;
1891
 
32839 amit.gupta 1892
                    brandAmountMap.put(brand, totalAmount);
30024 tejbeer 1893
 
35484 ranu 1894
                    brandQtyMap.put(brand, totalQty);
1895
 
32839 amit.gupta 1896
                }
30024 tejbeer 1897
 
32839 amit.gupta 1898
                fofoIdBrandAmountMap.put(customRetailer.getKey(), brandAmountMap);
35484 ranu 1899
                fofoIdBrandQtyMap.put(customRetailer.getKey(), brandQtyMap);
30024 tejbeer 1900
 
32839 amit.gupta 1901
            }
30024 tejbeer 1902
 
32839 amit.gupta 1903
            List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
1904
                    .selectAll(new ArrayList<>(fofoIdList), LocalDate.now().minusDays(1));
1905
            if (!partnerDailyInvestments.isEmpty()) {
1906
                partnerDailyInvestmentMap = partnerDailyInvestments.stream()
1907
                        .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1908
            }
30024 tejbeer 1909
 
32839 amit.gupta 1910
        }
33806 tejus.loha 1911
        Map<Integer, MonthlyTarget> fofoIdMonthlyTargetMap = monthlyTargetRepository.selectByDateAndFofoIds(YearMonth.now(), new ArrayList<>(fofoIds)).stream()
1912
                .collect(Collectors.toMap(MonthlyTarget::getFofoId, x -> x,
1913
                        (existing, replacement) -> replacement  // Keep the last entry
1914
                ));
1915
 
1916
        Map<Integer, Float> fofoMTDSaleMap = fofoOrderRepository.selectSaleSumGroupByFofoIds(YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now());
1917
 
1918
        Map<Integer, Double> currentMonthTillDateRetailerPOValueMap = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(new ArrayList<>(fofoIds),
1919
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
1920
                YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
1921
 
33812 tejus.loha 1922
        List<Loan> loans = loanRepository.selectAllActiveLoan().stream().filter(x -> fofoIds.contains(x.getFofoId())).collect(Collectors.toList());
1923
        Map<Integer, List<Loan>> loanMap = loans.stream().collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toList()));
1924
        Map<Integer, BigDecimal> totalDueMap = new HashMap<>();
1925
        for (Entry<Integer, List<Loan>> fofoIdLoanEntry : loanMap.entrySet()) {
1926
            List<Loan> Loans = fofoIdLoanEntry.getValue();
1927
            int fofoId = fofoIdLoanEntry.getKey();
1928
            BigDecimal totalDue = new BigDecimal(0);
1929
            for (Loan loan : Loans) {
1930
                BigDecimal pendingAmount = loan.getPendingAmount();
1931
                BigDecimal interestAccrued = loan.getInterestAccrued();
1932
                BigDecimal interestPaid = loan.getInterestPaid();
1933
                totalDue = totalDue.add(interestAccrued.subtract(interestPaid).add(pendingAmount));
1934
            }
1935
            totalDueMap.put(fofoId, totalDue);
1936
        }
1937
 
33813 tejus.loha 1938
 
32839 amit.gupta 1939
        //Only L3 and above can change the activationType
30024 tejbeer 1940
 
32839 amit.gupta 1941
        model.addAttribute("customRetailers", customRetailers);
33812 tejus.loha 1942
        model.addAttribute("totalDueMap", totalDueMap);
33806 tejus.loha 1943
        model.addAttribute("fofoMTDSaleMap", fofoMTDSaleMap);
1944
        model.addAttribute("fofoIdMonthlyTargetMap", fofoIdMonthlyTargetMap);
1945
        model.addAttribute("currentMonthTillDateRetailerPOValueMap", currentMonthTillDateRetailerPOValueMap);
30003 tejbeer 1946
 
34759 amit.gupta 1947
        //LOGGER.info("fofoIdBrandAmountMap" + fofoIdBrandAmountMap);
30003 tejbeer 1948
 
32839 amit.gupta 1949
        model.addAttribute("partnerDailyInvestmentMap", partnerDailyInvestmentMap);
30003 tejbeer 1950
 
32839 amit.gupta 1951
        model.addAttribute("brands", brands);
30003 tejbeer 1952
 
32839 amit.gupta 1953
        model.addAttribute("brandAmountLimit", Brand_Amount_Limit);
1954
        model.addAttribute("fofoIdBrandAmountMap", fofoIdBrandAmountMap);
35484 ranu 1955
        model.addAttribute("fofoIdBrandQtyMap", fofoIdBrandQtyMap);
30003 tejbeer 1956
 
32839 amit.gupta 1957
        model.addAttribute("inStockAccessTv", inStockAccessTv);
1958
        model.addAttribute("pendingIndentAccessTv", pendingIndentAccessTv);
1959
        model.addAttribute("grnPendingAccessTvOrders", grnPendingAccessTvOrders);
35490 ranu 1960
        model.addAttribute("inStockQtyAccessTv", inStockQtyAccessTv);
1961
        model.addAttribute("pendingIndentQtyAccessTv", pendingIndentQtyAccessTv);
1962
        model.addAttribute("grnPendingQtyAccessTvOrders", grnPendingQtyAccessTvOrders);
32839 amit.gupta 1963
        model.addAttribute("fofoIdPartnerTypeMap", fofoIdPartnerTypeMap);
30003 tejbeer 1964
 
1965
 
32839 amit.gupta 1966
        return "partner-brandwise-detail";
1967
    }
30046 tejbeer 1968
 
32839 amit.gupta 1969
    @RequestMapping(value = "/changeActivationType", method = RequestMethod.POST)
1970
    public String changeActivationType(HttpServletRequest request, @RequestParam String code,
1971
                                       @RequestParam ActivationType activationType, Model model) throws Exception {
30046 tejbeer 1972
 
32839 amit.gupta 1973
        FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(code);
30046 tejbeer 1974
 
32839 amit.gupta 1975
        fofoStore.setActivationType(activationType);
30046 tejbeer 1976
 
32839 amit.gupta 1977
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1978
        return "response";
30046 tejbeer 1979
 
32839 amit.gupta 1980
    }
30017 amit.gupta 1981
 
32839 amit.gupta 1982
    @RequestMapping(value = "/createPo", method = RequestMethod.POST)
1983
    public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1984
            throws Exception {
1985
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1986
        SuggestedPo mp = new SuggestedPo();
1987
        mp.setFofoId(monthlyPoModel.getFofoId());
1988
        mp.setCreateTimestamp(LocalDateTime.now());
1989
        mp.setStatus("open");
1990
        mp.setAuthId(loginDetails.getEmailId());
1991
        suggestedPoRepository.persist(mp);
30017 amit.gupta 1992
 
32839 amit.gupta 1993
        for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1994
            SuggestedPoDetail mpd = new SuggestedPoDetail();
1995
            mpd.setItemId(poId.getItemId());
1996
            mpd.setQuantity(poId.getQty());
1997
            mpd.setUpdatedTimestamp(LocalDateTime.now());
1998
            mpd.setPoId(mp.getId());
1999
            suggestedPoDetailRepository.persist(mpd);
2000
        }
30017 amit.gupta 2001
 
32839 amit.gupta 2002
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
2003
        sendNotificationModel.setCampaignName("Alert");
2004
        sendNotificationModel.setMessage("Suggested Po");
2005
        sendNotificationModel.setType("url");
2006
        sendNotificationModel.setTitle("Alert");
2007
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
2008
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2009
        sendNotificationModel.setMessageType(MessageType.notification);
2010
        int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
30017 amit.gupta 2011
 
32839 amit.gupta 2012
        sendNotificationModel.setUserIds(Arrays.asList(userId));
2013
        notificationService.sendNotification(sendNotificationModel);
2014
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
30017 amit.gupta 2015
 
32839 amit.gupta 2016
        return "response";
2017
    }
30003 tejbeer 2018
 
34087 ranu 2019
 
34437 ranu 2020
    @RequestMapping(value = "/createSuggestedPo", method = RequestMethod.POST)
2021
    public String createSuggestedPo(HttpServletRequest request, @RequestBody List<SuggestedPoCatalogModel> poCatalogModel, @RequestParam int fofoId, Model model)
2022
            throws Exception {
2023
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2024
        List<SuggestedPo> suggestedPos = suggestedPoRepository.selectAllOpenPoByFofoId(fofoId);
2025
        for (SuggestedPo suggestedPo : suggestedPos) {
2026
            suggestedPo.setStatus("closed");
2027
        }
2028
        SuggestedPo mp = new SuggestedPo();
2029
        mp.setFofoId(fofoId);
2030
        mp.setCreateTimestamp(LocalDateTime.now());
2031
        mp.setStatus("open");
2032
        mp.setAuthId(loginDetails.getEmailId());
2033
        suggestedPoRepository.persist(mp);
2034
 
2035
        for (SuggestedPoCatalogModel catalogModel : poCatalogModel) {
2036
            SuggestedPoDetail mpd = new SuggestedPoDetail();
34449 ranu 2037
            mpd.setItemId(catalogModel.getItemId());
34437 ranu 2038
            mpd.setQuantity(catalogModel.getQty());
2039
            mpd.setUpdatedTimestamp(LocalDateTime.now());
2040
            mpd.setPoId(mp.getId());
2041
            suggestedPoDetailRepository.persist(mpd);
2042
        }
2043
 
2044
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
2045
        sendNotificationModel.setCampaignName("Alert");
2046
        sendNotificationModel.setMessage("Suggested Po");
2047
        sendNotificationModel.setType("url");
2048
        sendNotificationModel.setTitle("Alert");
2049
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
2050
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
2051
        sendNotificationModel.setMessageType(MessageType.notification);
2052
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
2053
 
2054
        sendNotificationModel.setUserIds(Arrays.asList(userId));
2055
        notificationService.sendNotification(sendNotificationModel);
2056
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
2057
 
2058
        return "response";
2059
    }
2060
 
2061
 
34087 ranu 2062
    @RequestMapping(value = "/getPartnerShortageStockDetail", method = RequestMethod.GET)
2063
    public String getPartnerShortageStockDetail(HttpServletRequest request,
34098 ranu 2064
                                                @RequestParam(required = false, defaultValue = "") String brand, @RequestParam int fofoId, Model model)
32839 amit.gupta 2065
            throws Exception {
30003 tejbeer 2066
 
32839 amit.gupta 2067
        Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService
2068
                .getSaholicPOItems();
30003 tejbeer 2069
 
32839 amit.gupta 2070
        List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
2071
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2072
        Map<Integer, Integer> processingOrderMap = null;
2073
        Map<Integer, Integer> catalogIdAndQtyMap = null;
2074
        Map<Integer, Integer> grnPendingOrdersMap = null;
30044 tejbeer 2075
 
34490 ranu 2076
        Map<String, Set<PartnerStockDetailModel>> brandToUniqueItemsMap = new HashMap<>();
34449 ranu 2077
 
34490 ranu 2078
        List<PartnerStockDetailModel> inStocks = new ArrayList<>();
2079
        Map<String, PartnerStockDetailModel> inStocksDescriptionModelMap = new HashMap<>();
30044 tejbeer 2080
 
34490 ranu 2081
        List<PartnerStockDetailModel> grnPendings = new ArrayList<>();
2082
        Map<String, PartnerStockDetailModel> grnPendingsDescriptionModelMap = new HashMap<>();
30044 tejbeer 2083
 
34449 ranu 2084
 
34490 ranu 2085
        List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();
2086
        Map<String, PartnerStockDetailModel> pendingIndentsDescriptionModelMap = new HashMap<>();
30003 tejbeer 2087
 
32839 amit.gupta 2088
        Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
2089
                .stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
30003 tejbeer 2090
 
34425 ranu 2091
 
32839 amit.gupta 2092
        if (!currentInventorySnapshot.isEmpty()) {
34425 ranu 2093
            catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
2094
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2095
                            Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
34490 ranu 2096
            inStocks.addAll(getBrandItemwiseDetail(brand, catalogIdAndQtyMap));
34449 ranu 2097
            inStocksDescriptionModelMap = inStocks.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
32839 amit.gupta 2098
        }
34449 ranu 2099
 
32839 amit.gupta 2100
        Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
2101
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2102
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2103
        if (!grnPendingOrders.isEmpty()) {
34425 ranu 2104
            grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
2105
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2106
                            Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
34490 ranu 2107
            grnPendings.addAll(getBrandItemwiseDetail(brand, grnPendingOrdersMap));
34449 ranu 2108
            grnPendingsDescriptionModelMap = grnPendings.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
30003 tejbeer 2109
 
32839 amit.gupta 2110
        }
30003 tejbeer 2111
 
32839 amit.gupta 2112
        Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
2113
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2114
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2115
        if (!processingOrder.isEmpty()) {
34425 ranu 2116
            processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
2117
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2118
                            Collectors.summingInt(x -> processingOrder.get(x.getId()))));
34490 ranu 2119
            pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));
34449 ranu 2120
            pendingIndentsDescriptionModelMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
30003 tejbeer 2121
 
32839 amit.gupta 2122
        }
30003 tejbeer 2123
 
32839 amit.gupta 2124
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
2125
                .collect(Collectors.toList());
2126
        LOGGER.info("regionIds" + regionIds);
2127
        if (regionIds.size() == 0) {
2128
            LOGGER.info("No region found for partner {}", fofoId);
30003 tejbeer 2129
 
32839 amit.gupta 2130
        }
34456 ranu 2131
 
2132
//        this code is using for focusedModel()
32839 amit.gupta 2133
        Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository
2134
                .selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,
2135
                        Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
30003 tejbeer 2136
 
32839 amit.gupta 2137
        for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
2138
            List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());
30003 tejbeer 2139
 
32839 amit.gupta 2140
            if (brand.equals("undefined") || items.get(0).getBrand().equals(brand)) {
30003 tejbeer 2141
 
32839 amit.gupta 2142
                FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(), entry.getKey(),
2143
                        processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2144
                        warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2145
 
32839 amit.gupta 2146
                focusedModelShortageList.add(fm);
2147
            } else if (brand.equals("accessories")) {
30003 tejbeer 2148
 
32839 amit.gupta 2149
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2150
                    if (items.get(0).getCategoryId() != 0) {
2151
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30003 tejbeer 2152
 
32839 amit.gupta 2153
                        if (category.getParentCategoryId() == 10011) {
2154
                            FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2155
                                    entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2156
                                    warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2157
 
32839 amit.gupta 2158
                            focusedModelShortageList.add(fm);
30003 tejbeer 2159
 
32839 amit.gupta 2160
                        }
2161
                    }
30003 tejbeer 2162
 
32839 amit.gupta 2163
                }
30003 tejbeer 2164
 
32839 amit.gupta 2165
            } else if (brand.equals("TV")) {
30003 tejbeer 2166
 
32839 amit.gupta 2167
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2168
                    LOGGER.info("items.get(0).getCategoryId()" + items.get(0).getCategoryId());
2169
                    if (items.get(0).getCategoryId() != 0) {
30003 tejbeer 2170
 
32839 amit.gupta 2171
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30003 tejbeer 2172
 
32839 amit.gupta 2173
                        if (category.getParentCategoryId() == 14200) {
2174
                            FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2175
                                    entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2176
                                    warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2177
 
32839 amit.gupta 2178
                            focusedModelShortageList.add(fm);
30003 tejbeer 2179
 
32839 amit.gupta 2180
                        }
2181
                    }
30003 tejbeer 2182
 
32839 amit.gupta 2183
                }
30003 tejbeer 2184
 
32839 amit.gupta 2185
            }
30003 tejbeer 2186
 
32839 amit.gupta 2187
        }
30003 tejbeer 2188
 
34490 ranu 2189
        List<PartnerStockDetailModel> allStockItems = new ArrayList<>();
34449 ranu 2190
        allStockItems.addAll(inStocks);
2191
        allStockItems.addAll(grnPendings);
2192
        allStockItems.addAll(pendingIndents);
34760 amit.gupta 2193
        //LOGGER.info("allStockItems {}", allStockItems);
34449 ranu 2194
        brandToUniqueItemsMap =
2195
                allStockItems.stream().collect(
2196
                        Collectors.groupingBy(
34490 ranu 2197
                                PartnerStockDetailModel::getBrand,
34449 ranu 2198
                                Collectors.toSet()
2199
                        )
2200
                );
30003 tejbeer 2201
 
34449 ranu 2202
 
32839 amit.gupta 2203
        model.addAttribute("focusedModelShortageList", focusedModelShortageList);
30044 tejbeer 2204
 
32839 amit.gupta 2205
        model.addAttribute("inStocks", inStocks);
34449 ranu 2206
        model.addAttribute("inStocksDescriptionModelMap", inStocksDescriptionModelMap);
30044 tejbeer 2207
 
34449 ranu 2208
        model.addAttribute("brandToUniqueItemsMap", brandToUniqueItemsMap);
34490 ranu 2209
        model.addAttribute("fofoId", fofoId);
34425 ranu 2210
 
32839 amit.gupta 2211
        model.addAttribute("grnPendings", grnPendings);
34449 ranu 2212
        model.addAttribute("grnPendingsDescriptionModelMap", grnPendingsDescriptionModelMap);
30044 tejbeer 2213
 
32839 amit.gupta 2214
        model.addAttribute("pendingIndents", pendingIndents);
34449 ranu 2215
        model.addAttribute("pendingIndentsDescriptionModelMap", pendingIndentsDescriptionModelMap);
30044 tejbeer 2216
 
32839 amit.gupta 2217
        model.addAttribute("customRetailer", customRetailer);
30044 tejbeer 2218
 
32839 amit.gupta 2219
        model.addAttribute("brand", brand);
30044 tejbeer 2220
 
32839 amit.gupta 2221
        if (brand.equals("undefined")) {
30044 tejbeer 2222
 
32839 amit.gupta 2223
            Map<String, List<FocusedModelShortageModel>> focusedModelShortageBrandMap = focusedModelShortageList
2224
                    .stream().collect(Collectors.groupingBy(x -> x.getBrandName()));
30044 tejbeer 2225
 
34490 ranu 2226
            Map<String, List<PartnerStockDetailModel>> inStockBrandMap = inStocks.stream()
32839 amit.gupta 2227
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2228
 
32839 amit.gupta 2229
            LOGGER.info("inStockBrandMap" + inStockBrandMap);
30044 tejbeer 2230
 
34490 ranu 2231
            Map<String, List<PartnerStockDetailModel>> grnPendingBrandMap = grnPendings.stream()
32839 amit.gupta 2232
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2233
 
32839 amit.gupta 2234
            LOGGER.info("grnPendingBrandMap" + grnPendingBrandMap);
30044 tejbeer 2235
 
34490 ranu 2236
            Map<String, List<PartnerStockDetailModel>> pendingIndentBrandMap = pendingIndents.stream()
32839 amit.gupta 2237
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2238
 
32839 amit.gupta 2239
            LOGGER.info("pendingIndentBrandMap" + pendingIndentBrandMap);
30044 tejbeer 2240
 
32839 amit.gupta 2241
            model.addAttribute("inStockBrandMap", inStockBrandMap);
30044 tejbeer 2242
 
32839 amit.gupta 2243
            model.addAttribute("grnPendingBrandMap", grnPendingBrandMap);
30044 tejbeer 2244
 
32839 amit.gupta 2245
            model.addAttribute("focusedModelShortageBrandMap", focusedModelShortageBrandMap);
30044 tejbeer 2246
 
32839 amit.gupta 2247
            model.addAttribute("pendingIndentBrandMap", pendingIndentBrandMap);
30003 tejbeer 2248
 
32839 amit.gupta 2249
        }
34035 ranu 2250
 
34087 ranu 2251
        return "partner-stock-detail";
2252
 
2253
    }
2254
 
34397 ranu 2255
 
34449 ranu 2256
    @RequestMapping(value = "/getPoCatalogsItems", method = RequestMethod.GET)
34581 ranu 2257
    public String getPoCatalogsItems(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, @RequestParam float price, Model model)
34449 ranu 2258
            throws Exception {
2259
        List<Item> poItems = itemRepository.selectAllByCatalogItemId(catalogId);
34581 ranu 2260
 
2261
        List<Integer> itemIds = poItems.stream().map(x -> x.getId()).collect(Collectors.toList());
2262
 
2263
        Map<Integer, Integer> saholicInventoryMap = saholicInventoryService.getTotalAvailabilityByItemIds(itemIds);
2264
 
2265
        Set<Integer> availableStockItemIds = saholicInventoryMap.entrySet().stream()
2266
                .filter(x -> x.getValue() > 0)
2267
                .map(Map.Entry::getKey)
2268
                .collect(Collectors.toSet());
2269
 
2270
        List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == warehouseId)).collect(Collectors.toList());
2271
 
2272
        Set<Integer> intransitItemIds = warehouseIntransitDataModels.stream()
2273
                .filter(x -> x.getQty() > 0)
2274
                .map(WarehouseIntransitDataModel::getItemId)
2275
                .collect(Collectors.toSet());
2276
 
2277
        // Filter intransitItemIds to only those in itemIds
2278
        Set<Integer> intransitItemIdsFiltered = new HashSet<>(intransitItemIds);
2279
        intransitItemIdsFiltered.retainAll(itemIds);
2280
 
2281
        Set<Integer> itemIdsWithBothStocks = new HashSet<>();
2282
        itemIdsWithBothStocks.addAll(intransitItemIdsFiltered); // keeps only the common ones
2283
        itemIdsWithBothStocks.addAll(availableStockItemIds); // keeps only the common ones
2284
 
2285
        LOGGER.info("itemIds {}", itemIds);
2286
        LOGGER.info("itemIdsWithBothStocks {}", itemIdsWithBothStocks);
2287
        LOGGER.info("availableStockItemIds {}", availableStockItemIds);
2288
        LOGGER.info("intransitItemIdsFiltered {}", intransitItemIdsFiltered);
2289
        List<Item> instockItems = itemRepository.selectByIds(itemIdsWithBothStocks);
2290
 
2291
        model.addAttribute("poItems", instockItems);
34449 ranu 2292
        model.addAttribute("price", price);
2293
 
2294
        return "po-catalog-items";
2295
    }
2296
 
2297
 
34490 ranu 2298
    @RequestMapping(value = "/getItemsByCatalog", method = RequestMethod.GET)
2299
    public ResponseEntity<?> getItemsByCatalog(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int fofoId, Model model)
2300
            throws Exception {
2301
        List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
34495 ranu 2302
        Map<Integer, Item> itemMap = items.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
34490 ranu 2303
        Set<Integer> itemSet = items.stream().map(x -> x.getId()).collect(Collectors.toSet());
2304
        List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemSet);
34495 ranu 2305
        List<InStockItemDetailModel> inStockItemDetailModels = new ArrayList<>();
2306
        for (CurrentInventorySnapshot snap : currentInventorySnapshots) {
2307
            InStockItemDetailModel inStockItemDetailModel = new InStockItemDetailModel();
2308
            inStockItemDetailModel.setAvailability(snap.getAvailability());
2309
            inStockItemDetailModel.setItemId(snap.getItemId());
2310
            inStockItemDetailModel.setCatalogId(itemMap.get(snap.getItemId()).getCatalogItemId());
2311
            inStockItemDetailModel.setItemDescription(itemMap.get(snap.getItemId()).getItemDescription());
2312
            inStockItemDetailModel.setFofoId(snap.getFofoId());
2313
            inStockItemDetailModels.add(inStockItemDetailModel);
2314
        }
2315
 
2316
        return responseSender.ok(inStockItemDetailModels);
34490 ranu 2317
    }
34449 ranu 2318
 
34580 ranu 2319
    @Autowired
2320
    FofoOpeningStockRepository fofoOpeningStockRepository;
34449 ranu 2321
 
34087 ranu 2322
    @RequestMapping(value = "/getPartnerShortageStock", method = RequestMethod.GET)
2323
    public String getPartnerShortageStock(HttpServletRequest request,
35011 ranu 2324
                                          @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 2325
            throws Exception {
2326
 
34384 ranu 2327
        LocalDateTime presentDate = LocalDateTime.now();
34397 ranu 2328
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
34384 ranu 2329
 
34035 ranu 2330
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
34087 ranu 2331
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
34035 ranu 2332
 
34581 ranu 2333
        int warehouseId = fofoStore.getWarehouseId();
2334
 
34389 ranu 2335
        List<BrandWisePartnerSaleModel> brandWisePartnerSaleModels = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(Arrays.asList(fofoId));
2336
        LOGGER.info("brandWisePartnerSaleModels {}", brandWisePartnerSaleModels);
2337
 
2338
        Map<String, Long> brandToMtdMap = brandWisePartnerSaleModels.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getMtd()));
2339
 
34397 ranu 2340
        Map<Integer, Double> secondaryMtd = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
2341
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
2342
                curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
2343
 
2344
        double purchaseMtd = secondaryMtd.getOrDefault(fofoId, 0.0);
2345
 
2346
        Map<Integer, Double> secondaryToday = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
2347
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
2348
                curDate, curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
2349
 
2350
        double purchasedFtd = secondaryToday.getOrDefault(fofoId, 0.0);
2351
 
34412 ranu 2352
        MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
2353
 
34642 ranu 2354
        double purchaseTargetFtd = rbmTargetService.calculateFofoIdTodayTarget(fofoId, purchaseMtd, LocalDate.now());
34397 ranu 2355
 
2356
        double saleMtd = (Double) fofoUser.getSales(fofoId).get("mtdSale");
2357
 
2358
        double recoverableAmount = saleMtd - purchaseMtd;
2359
 
2360
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
34412 ranu 2361
 
34397 ranu 2362
        UserWallet userWallet = walletService.getUserWallet(fofoId);
2363
 
34412 ranu 2364
        BigDecimal totalAvailableFunds = sdCreditRequirement.getAvailableLimit().add(BigDecimal.valueOf(userWallet.getAmount()));
34397 ranu 2365
 
2366
        List<Loan> loans = loanRepository.selectActiveLoan(fofoId);
34412 ranu 2367
        double totalPendingAmount = loans.stream()
2368
                .map(Loan::getPendingAmount)
2369
                .mapToDouble(BigDecimal::doubleValue)
2370
                .sum();
2371
 
34397 ranu 2372
        boolean isLoanPending = false;
2373
        if (loans.size() > 0) {
2374
            isLoanPending = true;
2375
        }
2376
 
34389 ranu 2377
 
34035 ranu 2378
        List<PartnerWarehouseStockSummaryModel> partnerWarehouseStockSummaryModels = saholicInventoryService.getSaholicAndPartnerStock(fofoId, fofoStore.getWarehouseId());
2379
 
34569 ranu 2380
        List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == fofoStore.getWarehouseId())).collect(Collectors.toList());
2381
 
34589 ranu 2382
        Map<Integer, Long> catalogWiseQtyMap = new HashMap<>();
2383
        Set<Integer> inTransitCatalogIds = new HashSet<>();
2384
        List<PartnerWarehouseStockSummaryModel> intransistSummaryList = new ArrayList<>();
2385
        if (warehouseIntransitDataModels.size() > 0) {
2386
            Map<Integer, List<WarehouseIntransitDataModel>> warewarehouseIntransitDataModelsMap = warehouseIntransitDataModels.stream().collect(Collectors.groupingBy(WarehouseIntransitDataModel::getCatalogId));
34580 ranu 2387
 
34589 ranu 2388
            catalogWiseQtyMap = warehouseIntransitDataModels.stream()
2389
                    .collect(Collectors.groupingBy(
2390
                            WarehouseIntransitDataModel::getCatalogId,
2391
                            Collectors.summingLong(WarehouseIntransitDataModel::getQty)
2392
                    ));
34569 ranu 2393
 
34589 ranu 2394
            LOGGER.info("catalogWiseQtyMap key set {}", catalogWiseQtyMap.keySet());
34035 ranu 2395
 
34589 ranu 2396
            List<FofoOpeningStock> fofoOpeningStocksLitsForIntransist = fofoOpeningStockRepository.fofoOpeningStockByFofoId(catalogWiseQtyMap.keySet(), fofoId);
2397
            LOGGER.info("fofoOpeningStocksLitsForIntransist {}", fofoOpeningStocksLitsForIntransist);
2398
            // Optional: Build a map for faster lookup
2399
            Map<Integer, FofoOpeningStock> inTransistfofoOpeningStockMap = fofoOpeningStocksLitsForIntransist.stream()
2400
                    .collect(Collectors.toMap(FofoOpeningStock::getCatalogId, stock -> stock));
34437 ranu 2401
 
2402
 
34589 ranu 2403
            for (Map.Entry<Integer, Long> entry : catalogWiseQtyMap.entrySet()) {
2404
                int catalogId = entry.getKey();
2405
                long netAvailability = entry.getValue();
34580 ranu 2406
 
34589 ranu 2407
                FofoOpeningStock openingStock = inTransistfofoOpeningStockMap.get(catalogId);
2408
                WarehouseIntransitDataModel warehouseIntransitDataModel = warewarehouseIntransitDataModelsMap.get(catalogId).get(0);
34580 ranu 2409
 
34589 ranu 2410
                PartnerWarehouseStockSummaryModel inTransistmodel = new PartnerWarehouseStockSummaryModel(
2411
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getBrand() : "Unknown",
2412
                        catalogId,
2413
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getItemDescription() : "Unknown",
2414
                        warehouseIntransitDataModel != null ? 10006 : 0,
2415
                        (int) netAvailability,
2416
                        openingStock != null ? openingStock.getOpeningQty() : 0,
2417
                        openingStock != null ? openingStock.getCurrentQty() : 0,
2418
                        openingStock != null ? (openingStock.getOpeningQty() - openingStock.getCurrentQty()) : 0,
2419
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getStatus() : "Unknown"
2420
                );
34580 ranu 2421
 
34589 ranu 2422
                intransistSummaryList.add(inTransistmodel);
2423
            }
34580 ranu 2424
        }
2425
 
34589 ranu 2426
 
34490 ranu 2427
        List<DateWiseSoldCatalogQtyModel> sevenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(7));
34384 ranu 2428
 
34490 ranu 2429
        List<DateWiseSoldCatalogQtyModel> fourteenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(14));
34384 ranu 2430
 
34490 ranu 2431
        List<DateWiseSoldCatalogQtyModel> twentyOneDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(21));
34412 ranu 2432
 
34384 ranu 2433
        LOGGER.info("twentyOneDayAboveSoldsCatalogs {}", twentyOneDayAboveSoldsCatalogs);
34412 ranu 2434
 
34490 ranu 2435
        List<DateWiseSoldCatalogQtyModel> twentyEightDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(28));
34384 ranu 2436
 
34580 ranu 2437
        Set<Integer> catalogIds = partnerWarehouseStockSummaryModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
34412 ranu 2438
 
34589 ranu 2439
        if (!catalogWiseQtyMap.isEmpty()) {
2440
            inTransitCatalogIds = catalogWiseQtyMap.keySet().stream().filter(catalogId -> !catalogIds.contains(catalogId)).collect(Collectors.toSet());
2441
        }
34580 ranu 2442
 
2443
        // Add the missing IDs to the original set
2444
        catalogIds.addAll(inTransitCatalogIds);
2445
 
2446
        List<Integer> catalogsList = new ArrayList<>(catalogIds);
2447
 
2448
        Map<Integer, TagListing> tagListingsMap = tagListingRepository.selectAllByCatalogIds(catalogsList);
2449
 
34035 ranu 2450
        List<CatalogAgingModel> catalogAgingModels = ageingService.getCatalogsAgingByWarehouse(catalogIds, fofoStore.getWarehouseId());
2451
 
2452
        Map<Integer, CatalogAgingModel> catalogAgingModelMap = catalogAgingModels.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
2453
 
2454
        List<PartnerWarehouseStockAgingSummaryModel> partnerWarehouseStockAgingSummaryModelList = new ArrayList<>();
2455
 
2456
        for (PartnerWarehouseStockSummaryModel stockSummary : partnerWarehouseStockSummaryModels) {
2457
 
2458
            PartnerWarehouseStockAgingSummaryModel partnerWarehouseStockAgingSummaryModel = new PartnerWarehouseStockAgingSummaryModel();
2459
            partnerWarehouseStockAgingSummaryModel.setCatalogId(stockSummary.getCatalogId());
2460
            partnerWarehouseStockAgingSummaryModel.setBrand(stockSummary.getBrand());
2461
            partnerWarehouseStockAgingSummaryModel.setModelNumber(stockSummary.getModelNumber());
2462
            partnerWarehouseStockAgingSummaryModel.setNetAvailability(stockSummary.getShaholicNetAvailability());
2463
            partnerWarehouseStockAgingSummaryModel.setPartnerStockAvailability(stockSummary.getPartnerFullFilledQty());
2464
            partnerWarehouseStockAgingSummaryModel.setPartnerCurrentAvailability(stockSummary.getPartnerCurrentQty());
2465
            partnerWarehouseStockAgingSummaryModel.setPartnerShortageStock(stockSummary.getPartnerShortageQty());
34472 ranu 2466
            if (catalogAgingModelMap.get(stockSummary.getCatalogId()) != null) {
2467
                partnerWarehouseStockAgingSummaryModel.setExceedDays(catalogAgingModelMap.get(stockSummary.getCatalogId()).getExceedDays());
34489 ranu 2468
            } else {
2469
                partnerWarehouseStockAgingSummaryModel.setExceedDays(0);
2470
 
34472 ranu 2471
            }
34035 ranu 2472
            partnerWarehouseStockAgingSummaryModel.setStatus(stockSummary.getStatus());
2473
 
2474
            partnerWarehouseStockAgingSummaryModelList.add(partnerWarehouseStockAgingSummaryModel);
2475
        }
2476
 
34580 ranu 2477
        Set<Integer> existingCatalogIdsInAgingSummaryList = partnerWarehouseStockAgingSummaryModelList.stream()
2478
                .map(PartnerWarehouseStockAgingSummaryModel::getCatalogId)
2479
                .collect(Collectors.toSet());
34389 ranu 2480
 
34589 ranu 2481
        if (intransistSummaryList.size() > 0) {
2482
            // Step 2: Iterate over intransitSummaryList and add missing ones
2483
            for (PartnerWarehouseStockSummaryModel intransitStock : intransistSummaryList) {
2484
                if (!existingCatalogIdsInAgingSummaryList.contains(intransitStock.getCatalogId())) {
2485
                    PartnerWarehouseStockAgingSummaryModel agingModel = new PartnerWarehouseStockAgingSummaryModel();
2486
                    agingModel.setCatalogId(intransitStock.getCatalogId());
2487
                    agingModel.setBrand(intransitStock.getBrand());
2488
                    agingModel.setModelNumber(intransitStock.getModelNumber());
2489
                    agingModel.setNetAvailability(0); // Not part of original aging summary
2490
                    agingModel.setPartnerStockAvailability(intransitStock.getPartnerFullFilledQty());
2491
                    agingModel.setPartnerCurrentAvailability(intransitStock.getPartnerCurrentQty());
2492
                    agingModel.setPartnerShortageStock(intransitStock.getPartnerShortageQty());
2493
                    if (catalogAgingModelMap.get(intransitStock.getCatalogId()) != null) {
2494
                        agingModel.setExceedDays(catalogAgingModelMap.get(intransitStock.getCatalogId()).getExceedDays());
2495
                    } else {
2496
                        agingModel.setExceedDays(0);
2497
                    }
2498
                    agingModel.setStatus(intransitStock.getStatus() == null ? "OTHER" : intransitStock.getStatus());
2499
 
2500
                    partnerWarehouseStockAgingSummaryModelList.add(agingModel);
34580 ranu 2501
                }
2502
            }
2503
        }
2504
 
2505
 
34384 ranu 2506
        List<String> statusOrder = Arrays.asList("HID", "FASTMOVING", "RUNNING", "SLOWMOVING", "OTHER");
34035 ranu 2507
 
2508
        Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> brandStatusWiseStockListMap =
2509
                partnerWarehouseStockAgingSummaryModelList.stream().collect(Collectors.groupingBy(
2510
                        PartnerWarehouseStockAgingSummaryModel::getBrand,
2511
                        Collectors.groupingBy(PartnerWarehouseStockAgingSummaryModel::getStatus)
2512
                ));
34389 ranu 2513
//map of list as hid,fast,slow and other in last otherwise other is coming in start (here is using status order)
34035 ranu 2514
        Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> sortedBrandStatusWiseStockListMap =
2515
                brandStatusWiseStockListMap.entrySet().stream().collect(Collectors.toMap(
2516
                        Map.Entry::getKey, // Key (Brand)
2517
                        entry -> {
2518
                            Map<String, List<PartnerWarehouseStockAgingSummaryModel>> sortedStatusMap = entry.getValue().entrySet().stream()
2519
                                    .sorted((e1, e2) -> Integer.compare(
2520
                                            statusOrder.indexOf(e1.getKey()),
2521
                                            statusOrder.indexOf(e2.getKey())
2522
                                    ))
2523
                                    .collect(Collectors.toMap(
2524
                                            Map.Entry::getKey,
2525
                                            Map.Entry::getValue,
2526
                                            (v1, v2) -> v1,
2527
                                            LinkedHashMap::new // Ensure ordering is maintained
2528
                                    ));
2529
                            return sortedStatusMap;
2530
                        },
2531
                        (v1, v2) -> v1,
2532
                        LinkedHashMap::new // Maintain order of brands
2533
                ));
34490 ranu 2534
        LOGGER.info("brandToMtdMap {}", brandToMtdMap);
34454 ranu 2535
        List<String> sortedBrandsByMtd = brandToMtdMap.entrySet()
2536
                .stream()
2537
                .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // Descending MTD
2538
                .map(Map.Entry::getKey)
2539
                .collect(Collectors.toList());
2540
 
2541
        List<String> remainingBrands = ProfitMandiConstants.BRANDS.stream()
2542
                .filter(x -> !brandToMtdMap.containsKey(x))
2543
                .filter(x -> sortedBrandStatusWiseStockListMap.containsKey(x))
2544
                .collect(Collectors.toList());
2545
        List<String> remainingBrandsWithoutStock = ProfitMandiConstants.BRANDS.stream()
2546
                .filter(x -> !brandToMtdMap.containsKey(x))
2547
                .filter(x -> !sortedBrandStatusWiseStockListMap.containsKey(x)) // no stock
2548
                .collect(Collectors.toList());
2549
 
34683 ranu 2550
        List<InStockBrandItemModel> inStockBrandItemModels = currentInventorySnapshotRepository.selectInStockItemsByBrand(fofoId);
2551
 
2552
        Map<String, Long> brandsWithPartnerStockMap = inStockBrandItemModels.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand, Collectors.summingLong(InStockBrandItemModel::getQty)));
2553
        List<String> brandsWithPartnerStock = brandsWithPartnerStockMap.entrySet().stream().filter(x -> x.getValue() > 0).map(x -> x.getKey()).collect(Collectors.toList());
34513 ranu 2554
        List<String> sortedBrands = new ArrayList<>();
2555
        sortedBrands.addAll(sortedBrandsByMtd);
2556
        sortedBrands.addAll(remainingBrands);
2557
        sortedBrands.addAll(remainingBrandsWithoutStock);
34454 ranu 2558
 
34513 ranu 2559
        List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
2560
 
2561
        List<String> finalSortedBrands = sortedBrands.stream().filter(x -> !partnerIneligibleBrands.contains(x) && !"itel".equalsIgnoreCase(x)).collect(Collectors.toList());
2562
 
34487 ranu 2563
        Map<Integer, Integer> processingOrderMap = null;
2564
        List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();
2565
        Map<Integer, PartnerStockDetailModel> pendingIndentsDetailMap = new HashMap<>();
2566
 
2567
        Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
2568
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2569
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2570
        if (!processingOrder.isEmpty()) {
2571
            processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
2572
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2573
                            Collectors.summingInt(x -> processingOrder.get(x.getId()))));
2574
            pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));
2575
            pendingIndentsDetailMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
2576
 
2577
        }
2578
        LOGGER.info("pendingIndents {}", pendingIndents);
2579
        LOGGER.info("pendingIndentsDetailMap {}", pendingIndentsDetailMap);
2580
 
34035 ranu 2581
        model.addAttribute("brandStatusWiseStockListMap", sortedBrandStatusWiseStockListMap);
34683 ranu 2582
        model.addAttribute("brandsWithPartnerStock", brandsWithPartnerStock);
34487 ranu 2583
        model.addAttribute("pendingIndentsDetailMap", pendingIndentsDetailMap);
34412 ranu 2584
        model.addAttribute("brands", finalSortedBrands);
2585
        model.addAttribute("brandToMtdMap", brandToMtdMap);
34569 ranu 2586
        model.addAttribute("catalogWiseQtyMap", catalogWiseQtyMap);
34580 ranu 2587
        model.addAttribute("intransistSummaryList", intransistSummaryList);
34087 ranu 2588
        model.addAttribute("brand", brand);
2589
        model.addAttribute("fofoId", fofoId);
34581 ranu 2590
        model.addAttribute("warehouseId", warehouseId);
34087 ranu 2591
        model.addAttribute("customRetailer", customRetailer);
34397 ranu 2592
        model.addAttribute("shortInvest", shortInvest);
35011 ranu 2593
        model.addAttribute("totalDueWithInterest", totalDueWithInterest);
34397 ranu 2594
        model.addAttribute("purchaseMtd", purchaseMtd);
2595
        model.addAttribute("purchasedFtd", purchasedFtd);
2596
        model.addAttribute("saleMtd", saleMtd);
2597
        model.addAttribute("purchaseTargetFtd", purchaseTargetFtd);
2598
        model.addAttribute("recoverableAmount", recoverableAmount);
2599
        model.addAttribute("isLoanPending", isLoanPending);
2600
        model.addAttribute("totalAvailableFunds", totalAvailableFunds);
34412 ranu 2601
        model.addAttribute("sdCreditRequirement", sdCreditRequirement);
2602
        model.addAttribute("userWallet", userWallet);
2603
        model.addAttribute("monthlyTarget", monthlyTarget);
2604
        model.addAttribute("totalPendingAmount", totalPendingAmount);
34437 ranu 2605
        model.addAttribute("tagListingsMap", tagListingsMap);
34412 ranu 2606
        model.addAttribute("sevenDayAboveSoldsCatalogs", sevenDayAboveSoldsCatalogs);
2607
        model.addAttribute("fourteenDayAboveSoldsCatalogs", fourteenDayAboveSoldsCatalogs);
2608
        model.addAttribute("twentyOneDayAboveSoldsCatalogs", twentyOneDayAboveSoldsCatalogs);
2609
        model.addAttribute("twentyEightDayAboveSoldsCatalogs", twentyEightDayAboveSoldsCatalogs);
32839 amit.gupta 2610
        return "partner-stock";
30003 tejbeer 2611
 
32839 amit.gupta 2612
    }
30044 tejbeer 2613
 
32839 amit.gupta 2614
    private List<PartnerStockDescriptionModel> getBrandItemwiseDescription(String brand,
2615
                                                                           Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
2616
        List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();
30044 tejbeer 2617
 
32839 amit.gupta 2618
        for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2619
            List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
30044 tejbeer 2620
 
32839 amit.gupta 2621
            if (brand.equals("accessories")) {
2622
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
30044 tejbeer 2623
 
32839 amit.gupta 2624
                    if (items.get(0).getCategoryId() != 0) {
2625
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30044 tejbeer 2626
 
32839 amit.gupta 2627
                        if (category.getParentCategoryId() == 10011) {
2628
                            PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2629
                            psdp.setBrand(items.get(0).getBrand());
2630
                            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2631
                                    + items.get(0).getModelNumber());
2632
                            psdp.setQty(inStock.getValue());
2633
                            inStocks.add(psdp);
2634
                        }
2635
                    }
30044 tejbeer 2636
 
32839 amit.gupta 2637
                }
30044 tejbeer 2638
 
32839 amit.gupta 2639
            } else if (brand.equals("TV")) {
2640
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
30044 tejbeer 2641
 
32839 amit.gupta 2642
                    if (items.get(0).getCategoryId() != 0) {
2643
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30044 tejbeer 2644
 
32839 amit.gupta 2645
                        if (category.getParentCategoryId() == 14200) {
2646
                            PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2647
                            psdp.setBrand(items.get(0).getBrand());
2648
                            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2649
                                    + items.get(0).getModelNumber());
2650
                            psdp.setQty(inStock.getValue());
2651
                            inStocks.add(psdp);
2652
                        }
2653
                    }
30044 tejbeer 2654
 
32839 amit.gupta 2655
                }
30044 tejbeer 2656
 
32839 amit.gupta 2657
            } else {
2658
                PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2659
                psdp.setBrand(items.get(0).getBrand());
2660
                psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2661
                        + items.get(0).getModelNumber());
2662
                psdp.setQty(inStock.getValue());
2663
                inStocks.add(psdp);
2664
            }
30044 tejbeer 2665
 
32839 amit.gupta 2666
        }
30044 tejbeer 2667
 
32839 amit.gupta 2668
        return inStocks;
2669
    }
30003 tejbeer 2670
 
34487 ranu 2671
    private List<PartnerStockDetailModel> getBrandItemwiseDetail(String brand,
2672
                                                                 Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
2673
        List<PartnerStockDetailModel> inStocks = new ArrayList<>();
2674
 
2675
        for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2676
            List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
2677
            PartnerStockDetailModel psdp = new PartnerStockDetailModel();
2678
            psdp.setBrand(items.get(0).getBrand());
2679
            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2680
                    + items.get(0).getModelNumber());
2681
            psdp.setQty(inStock.getValue());
2682
            psdp.setCatalogId(items.get(0).getCatalogItemId());
2683
            inStocks.add(psdp);
2684
        }
2685
 
2686
        return inStocks;
2687
    }
2688
 
32839 amit.gupta 2689
    private FocusedModelShortageModel getFocusedModelShortage(int qty, int catalogId,
2690
                                                              Map<Integer, Integer> processingOrderMap, Map<Integer, Integer> grnPendingOrdersMap,
2691
                                                              Map<Integer, Integer> catalogIdAndQtyMap, int fofoId,
2692
                                                              Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap, List<Item> items,
2693
                                                              CustomRetailer customRetailer) throws ProfitMandiBusinessException {
30003 tejbeer 2694
 
32839 amit.gupta 2695
        int minQty = qty;
2696
        int inStockQty = 0;
2697
        int processingQty = 0;
2698
        int grnPendingQty = 0;
2699
        int allColorNetAvailability = 0;
2700
        int allColorPoAvailability = 0;
2701
        if (processingOrderMap != null) {
2702
            processingQty = (processingOrderMap.get(catalogId) == null) ? 0 : processingOrderMap.get(catalogId);
30003 tejbeer 2703
 
32839 amit.gupta 2704
        }
2705
        if (grnPendingOrdersMap != null) {
2706
            grnPendingQty = (grnPendingOrdersMap.get(catalogId) == null) ? 0 : grnPendingOrdersMap.get(catalogId);
30003 tejbeer 2707
 
32839 amit.gupta 2708
        }
2709
        if (catalogIdAndQtyMap != null) {
2710
            inStockQty = (catalogIdAndQtyMap.get(catalogId) == null) ? 0 : catalogIdAndQtyMap.get(catalogId);
30003 tejbeer 2711
 
32839 amit.gupta 2712
        }
30003 tejbeer 2713
 
32839 amit.gupta 2714
        int grnStockQty = grnPendingQty + inStockQty;
2715
        int totalQty = processingQty + grnPendingQty + inStockQty;
30003 tejbeer 2716
 
32839 amit.gupta 2717
        int shortageQty = minQty - totalQty;
2718
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
30003 tejbeer 2719
 
32839 amit.gupta 2720
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap
2721
                .get(fofoStore.getWarehouseId());
30003 tejbeer 2722
 
32839 amit.gupta 2723
        for (Item it : items) {
2724
            List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(it.getId(),
2725
                    fofoStore.getWarehouseId());
2726
            List<SaholicPOItem> poItemAvailability = null;
30003 tejbeer 2727
 
32839 amit.gupta 2728
            if (poItemAvailabilityMap != null) {
2729
                poItemAvailability = poItemAvailabilityMap.get(it.getId());
2730
            }
2731
            if (currentAvailability != null) {
2732
                allColorNetAvailability += currentAvailability.stream()
2733
                        .collect(Collectors.summingInt(SaholicCISTable::getNetAvailability));
2734
            }
30003 tejbeer 2735
 
32839 amit.gupta 2736
            if (poItemAvailability != null) {
2737
                allColorPoAvailability += poItemAvailability.stream()
2738
                        .collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
2739
            }
30003 tejbeer 2740
 
32839 amit.gupta 2741
        }
30003 tejbeer 2742
 
32839 amit.gupta 2743
        FocusedModelShortageModel fm = new FocusedModelShortageModel();
2744
        fm.setFofoId(fofoId);
2745
        fm.setStoreCode(fofoStore.getCode());
2746
        fm.setStoreName(customRetailer.getBusinessName());
2747
        fm.setBrandName(items.get(0).getBrand());
2748
        fm.setModelName(items.get(0).getModelName());
2749
        fm.setModelNumber(items.get(0).getModelNumber());
2750
        fm.setGrnStockQty(grnStockQty);
2751
        fm.setPendingIndentQty(processingQty);
2752
        fm.setShortageQty(shortageQty);
2753
        fm.setPoAvailability(allColorPoAvailability);
2754
        fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
2755
        fm.setAvailability(allColorNetAvailability);
2756
        return fm;
30003 tejbeer 2757
 
32839 amit.gupta 2758
    }
30017 amit.gupta 2759
 
32839 amit.gupta 2760
    @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.GET)
2761
    public String SendPONotification(HttpServletRequest request, Model model) {
2762
        model.addAttribute("warehouses", ProfitMandiConstants.WAREHOUSE_MAP);
2763
        return "send-po-notification";
2764
    }
30017 amit.gupta 2765
 
32839 amit.gupta 2766
    @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.POST)
2767
    public String sendPONotification(HttpServletRequest request, @RequestBody POItemWarehouseModel poItemWarehouseModel,
2768
                                     Model model) throws Exception {
30017 amit.gupta 2769
 
32839 amit.gupta 2770
        Map<Integer, Item> selectedCatalogItemMap = itemRepository
2771
                .selectAllByCatalogIds(new HashSet<>(poItemWarehouseModel.getCatalogIds())).stream()
2772
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x, (existing, replacement) -> existing));
30080 amit.gupta 2773
 
32839 amit.gupta 2774
        Set<String> brands = selectedCatalogItemMap.values().stream().map(x -> x.getBrand().toLowerCase())
2775
                .collect(Collectors.toSet());
30017 amit.gupta 2776
 
32839 amit.gupta 2777
        int warehouseId = poItemWarehouseModel.getWarehouseId();
2778
        for (String brand : brands) {
2779
            List<String> modelNames = selectedCatalogItemMap.entrySet().stream()
2780
                    .filter(x -> x.getValue().getBrand().toLowerCase().equals(brand))
2781
                    .map(x -> x.getValue().getItemDescriptionNoColor()).collect(Collectors.toList());
2782
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
2783
            sendNotificationModel.setCampaignName("SendPo");
2784
            sendNotificationModel.setTitle(String.format(PO_TITLE_STRING));
2785
            sendNotificationModel.setMessage(String.join(", ", modelNames));
2786
            sendNotificationModel.setType("url");
2787
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
2788
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2789
            sendNotificationModel.setMessageType(MessageType.notification);
30017 amit.gupta 2790
 
32839 amit.gupta 2791
            List<BrandRegionMapping> brandRegionMappings = brandRegionMappingRepository.selectAll().stream()
2792
                    .filter(x -> brand.equals(x.getBrand().toLowerCase()) && x.getFromWarehouseId() == warehouseId
2793
                            && !x.isAccessory())
2794
                    .collect(Collectors.toList());
2795
            List<Integer> toWarehouseIds = brandRegionMappings.stream().map(x -> x.getToWarehouseId())
2796
                    .collect(Collectors.toList());
30017 amit.gupta 2797
 
32839 amit.gupta 2798
            List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(toWarehouseIds).stream()
2799
                    .filter(x -> !x.isInternal() && x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
30017 amit.gupta 2800
 
32839 amit.gupta 2801
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
2802
            sendNotificationModel.setUserIds(userIds);
2803
            notificationService.sendNotification(sendNotificationModel);
2804
        }
2805
        model.addAttribute("response1", true);
2806
        return "response";
2807
    }
2808
 
25721 tejbeer 2809
}