Subversion Repositories SmartDukaan

Rev

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