Subversion Repositories SmartDukaan

Rev

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

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