Subversion Repositories SmartDukaan

Rev

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