Subversion Repositories SmartDukaan

Rev

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