Subversion Repositories SmartDukaan

Rev

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

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