Subversion Repositories SmartDukaan

Rev

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