Subversion Repositories SmartDukaan

Rev

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