Subversion Repositories SmartDukaan

Rev

Rev 34384 | Rev 34397 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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