Subversion Repositories SmartDukaan

Rev

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