Subversion Repositories SmartDukaan

Rev

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