Subversion Repositories SmartDukaan

Rev

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