Subversion Repositories SmartDukaan

Rev

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