Subversion Repositories SmartDukaan

Rev

Rev 37846 | 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
 
37846 amit 3
import com.spice.profitmandi.service.warehouse.BillingWarehouseService;
4
 
30046 tejbeer 5
import com.spice.profitmandi.common.enumuration.ActivationType;
23785 amit.gupta 6
import com.spice.profitmandi.common.enumuration.CounterSize;
26846 tejbeer 7
import com.spice.profitmandi.common.enumuration.MessageType;
23405 amit.gupta 8
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30017 amit.gupta 9
import com.spice.profitmandi.common.model.*;
24231 amit.gupta 10
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 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;
35236 amit 14
import com.spice.profitmandi.dao.entity.catalog.*;
27088 tejbeer 15
import com.spice.profitmandi.dao.entity.cs.Region;
30017 amit.gupta 16
import com.spice.profitmandi.dao.entity.fofo.*;
30664 amit.gupta 17
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
30003 tejbeer 18
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
33812 tejus.loha 19
import com.spice.profitmandi.dao.entity.transaction.Loan;
23796 amit.gupta 20
import com.spice.profitmandi.dao.entity.transaction.Order;
34397 ranu 21
import com.spice.profitmandi.dao.entity.transaction.SDCreditRequirement;
26846 tejbeer 22
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
30017 amit.gupta 23
import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;
26978 tejbeer 24
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
35765 ranu 25
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
26
import com.spice.profitmandi.dao.event.TagListingEventPublisher;
34389 ranu 27
import com.spice.profitmandi.dao.model.*;
26721 tejbeer 28
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
35765 ranu 29
import com.spice.profitmandi.dao.repository.catalog.*;
31663 amit.gupta 30
import com.spice.profitmandi.dao.repository.cs.*;
30044 tejbeer 31
import com.spice.profitmandi.dao.repository.dtr.BrandLimitRepository;
23779 amit.gupta 32
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 33
import com.spice.profitmandi.dao.repository.dtr.Mongo;
26846 tejbeer 34
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
30017 amit.gupta 35
import com.spice.profitmandi.dao.repository.fofo.*;
30664 amit.gupta 36
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
27768 tejbeer 37
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
30017 amit.gupta 38
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
33812 tejus.loha 39
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
23796 amit.gupta 40
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
34397 ranu 41
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
23796 amit.gupta 42
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
43
import com.spice.profitmandi.dao.repository.user.UserRepository;
30017 amit.gupta 44
import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;
35765 ranu 45
import com.spice.profitmandi.model.WarehouseItemQtyModel;
34397 ranu 46
import com.spice.profitmandi.service.FofoUser;
26846 tejbeer 47
import com.spice.profitmandi.service.NotificationService;
34397 ranu 48
import com.spice.profitmandi.service.RbmTargetService;
23798 amit.gupta 49
import com.spice.profitmandi.service.authentication.RoleManager;
34513 ranu 50
import com.spice.profitmandi.service.catalog.BrandsService;
34035 ranu 51
import com.spice.profitmandi.service.inventory.*;
37055 ranu 52
import com.spice.profitmandi.service.mail.MailOutboxService;
53
import com.spice.profitmandi.service.transaction.SDCreditService;
23779 amit.gupta 54
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 55
import com.spice.profitmandi.service.wallet.WalletService;
23405 amit.gupta 56
import com.spice.profitmandi.web.model.LoginDetails;
57
import com.spice.profitmandi.web.util.CookiesProcessor;
37977 aman 58
import com.spice.profitmandi.web.util.DishaRbmToken;
23405 amit.gupta 59
import com.spice.profitmandi.web.util.MVCResponseSender;
33910 amit.gupta 60
import in.shop2020.model.v1.order.OrderStatus;
30017 amit.gupta 61
import org.apache.commons.io.output.ByteArrayOutputStream;
62
import org.apache.logging.log4j.LogManager;
63
import org.apache.logging.log4j.Logger;
64
import org.json.JSONArray;
65
import org.json.JSONObject;
66
import org.springframework.beans.factory.annotation.Autowired;
37977 aman 67
import org.springframework.beans.factory.annotation.Value;
30017 amit.gupta 68
import org.springframework.core.io.ByteArrayResource;
69
import org.springframework.http.HttpHeaders;
70
import org.springframework.http.HttpStatus;
71
import org.springframework.http.ResponseEntity;
72
import org.springframework.mail.javamail.JavaMailSender;
73
import org.springframework.stereotype.Controller;
74
import org.springframework.transaction.annotation.Transactional;
75
import org.springframework.ui.Model;
76
import org.springframework.web.bind.annotation.RequestBody;
77
import org.springframework.web.bind.annotation.RequestMapping;
78
import org.springframework.web.bind.annotation.RequestMethod;
79
import org.springframework.web.bind.annotation.RequestParam;
23796 amit.gupta 80
 
30017 amit.gupta 81
import javax.servlet.http.HttpServletRequest;
33812 tejus.loha 82
import java.math.BigDecimal;
30017 amit.gupta 83
import java.time.LocalDate;
84
import java.time.LocalDateTime;
85
import java.time.LocalTime;
33806 tejus.loha 86
import java.time.YearMonth;
30017 amit.gupta 87
import java.util.*;
88
import java.util.Map.Entry;
89
import java.util.function.Function;
90
import java.util.stream.Collectors;
91
 
23405 amit.gupta 92
@Controller
93
@Transactional(rollbackFor = Throwable.class)
94
public class IndentController {
95
 
37846 amit 96
    @Autowired
97
    private BillingWarehouseService billingWarehouseService;
98
 
99
 
32839 amit.gupta 100
    private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
37977 aman 101
 
102
    // Key shared with chat.smartdukaan.com, only used to sign Disha passes (never sent to the page).
103
    // Set on the server only (-Ddisha.rbm.key=... in Tomcat's setenv.sh); empty = no Disha.
104
    @Value("${disha.rbm.key:}")
105
    private String dishaRbmKey;
106
    // Where Disha is served from; -Ddisha.server=http://localhost:8779 for a local test
107
    @Value("${disha.server:https://chat.smartdukaan.com}")
108
    private String dishaServer;
109
    private static final long DISHA_TOKEN_TTL_S = 4 * 60 * 60;
32839 amit.gupta 110
    private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 111
 
32839 amit.gupta 112
    private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
113
            OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
114
            OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
115
            OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 116
 
32839 amit.gupta 117
    private static final int PLANNING_OPEN_DAY = 20;
118
    private static final int PLANNING_CLOSE_DAY = 1;
26951 amit.gupta 119
 
32839 amit.gupta 120
    private static final String PO_TITLE_STRING = "Alert - Stock Arriving at SD Warehouse";
30017 amit.gupta 121
 
32839 amit.gupta 122
    @Autowired
123
    WalletService walletService;
24231 amit.gupta 124
 
32839 amit.gupta 125
    @Autowired
126
    BrandRegionMappingRepository brandRegionMappingRepository;
30017 amit.gupta 127
 
32839 amit.gupta 128
    @Autowired
129
    private JavaMailSender googleMailSender;
25721 tejbeer 130
 
32839 amit.gupta 131
    @Autowired
35957 amit 132
    private MailOutboxService mailOutboxService;
133
 
134
    @Autowired
34490 ranu 135
    private ResponseSender responseSender;
136
 
137
    @Autowired
32839 amit.gupta 138
    private CookiesProcessor cookiesProcessor;
24231 amit.gupta 139
 
32839 amit.gupta 140
    @Autowired
141
    private UserWalletRepository userWalletRepository;
23785 amit.gupta 142
 
32839 amit.gupta 143
    @Autowired
144
    private UserRepository userRepository;
23796 amit.gupta 145
 
32839 amit.gupta 146
    @Autowired
147
    FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 148
 
32839 amit.gupta 149
    @Autowired
150
    private OrderRepository orderRepository;
23796 amit.gupta 151
 
32839 amit.gupta 152
    @Autowired
153
    private UserAccountRepository userAccountRepository;
26846 tejbeer 154
 
32839 amit.gupta 155
    @Autowired
156
    private ItemRepository itemRepository;
23405 amit.gupta 157
 
32839 amit.gupta 158
    @Autowired
159
    private StockAllocationService stockAllocationService;
23779 amit.gupta 160
 
32839 amit.gupta 161
    @Autowired
162
    private RetailerService retailerService;
23405 amit.gupta 163
 
32839 amit.gupta 164
    @Autowired
165
    private TagListingRepository tagListingRepository;
23405 amit.gupta 166
 
32839 amit.gupta 167
    @Autowired
35547 amit 168
    private TagListingEventPublisher tagListingEventPublisher;
169
 
170
    @Autowired
32839 amit.gupta 171
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
23405 amit.gupta 172
 
32839 amit.gupta 173
    @Autowired
35771 ranu 174
    private InventoryItemRepository inventoryItemRepository;
175
 
176
    @Autowired
32839 amit.gupta 177
    private PurchaseRepository purchaseRepository;
23796 amit.gupta 178
 
32839 amit.gupta 179
    @Autowired
180
    private MVCResponseSender mvcResponseSender;
23405 amit.gupta 181
 
32839 amit.gupta 182
    @Autowired
183
    private FocusedModelRepository focusedModelRepository;
25721 tejbeer 184
 
32839 amit.gupta 185
    @Autowired
186
    private MonthlyPlannedRepository monthlyPlannedRepository;
25721 tejbeer 187
 
32839 amit.gupta 188
    @Autowired
189
    private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 190
 
32839 amit.gupta 191
    @Autowired
192
    private FofoOrderItemRepository fofoOrderItemRepository;
25732 tejbeer 193
 
32839 amit.gupta 194
    @Autowired
195
    private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 196
 
32839 amit.gupta 197
    @Autowired
198
    RoleManager roleManager;
23405 amit.gupta 199
 
32839 amit.gupta 200
    @Autowired
201
    PartnerTypeChangeRepository partnerTypeChangeRepository;
27081 tejbeer 202
 
32839 amit.gupta 203
    @Autowired
204
    private Mongo mongoClient;
25736 tejbeer 205
 
32839 amit.gupta 206
    @Autowired
207
    private InventoryService inventoryService;
25736 tejbeer 208
 
32839 amit.gupta 209
    @Autowired
210
    private CsService1 csService1;
31663 amit.gupta 211
 
32839 amit.gupta 212
    @Autowired
213
    private CsService csService;
25721 tejbeer 214
 
32839 amit.gupta 215
    @Autowired
216
    private AuthRepository authRepository;
217
    @Autowired
218
    WarehouseRepository warehouseRepository;
219
    @Autowired
220
    private SuggestedPoRepository suggestedPoRepository;
26846 tejbeer 221
 
32839 amit.gupta 222
    @Autowired
223
    private NotificationService notificationService;
26846 tejbeer 224
 
32839 amit.gupta 225
    @Autowired
226
    private RegionRepository regionRepository;
27088 tejbeer 227
 
32839 amit.gupta 228
    @Autowired
229
    private PartnerRegionRepository partnerRegionRepository;
27088 tejbeer 230
 
32839 amit.gupta 231
    @Autowired
232
    private SaholicInventoryCISRepository saholicInventoryCISRepository;
27768 tejbeer 233
 
32839 amit.gupta 234
    @Autowired
235
    private SaholicInventoryService saholicInventoryService;
27768 tejbeer 236
 
32839 amit.gupta 237
    @Autowired
238
    private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
239
    @Autowired
240
    private SuggestedPoDetailRepository suggestedPoDetailRepository;
30003 tejbeer 241
 
32839 amit.gupta 242
    @Autowired
243
    SaholicCISTableRepository saholicCISTableRepository;
30664 amit.gupta 244
 
33812 tejus.loha 245
    @Autowired
246
    MonthlyTargetRepository monthlyTargetRepository;
247
 
248
    @Autowired
34035 ranu 249
    AgeingService ageingService;
250
 
251
    @Autowired
33812 tejus.loha 252
    LoanRepository loanRepository;
253
 
34397 ranu 254
    @Autowired
35811 amit 255
    SDCreditService sdCreditService;
256
 
257
    @Autowired
34397 ranu 258
    RbmTargetService rbmTargetService;
259
 
260
    @Autowired
261
    FofoUser fofoUser;
262
 
263
    @Autowired
34513 ranu 264
    BrandsService brandsService;
265
 
266
    @Autowired
34397 ranu 267
    SDCreditRequirementRepository sdCreditRequirementRepository;
268
 
35765 ranu 269
    @Autowired
270
    CategorisedCatalogRepository categorisedCatalogRepository;
271
 
32839 amit.gupta 272
    @RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
273
    public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
274
                                 @RequestParam int itemQty, @RequestParam int fofoId) throws Exception {
275
        if (fofoId == 0) {
27088 tejbeer 276
 
32839 amit.gupta 277
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
278
            fofoId = loginDetails.getFofoId();
27088 tejbeer 279
 
32839 amit.gupta 280
        }
27088 tejbeer 281
 
32839 amit.gupta 282
        LocalDate currentMonthDate = LocalDate.now();
283
        MonthlyPlanned monthlyPlanned = null;
25721 tejbeer 284
 
32839 amit.gupta 285
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
286
            currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
287
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
288
            LOGGER.info("monthlyPlanned" + monthlyPlanned);
289
            saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);
290
        }
291
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
292
        return "response";
293
    }
26082 tejbeer 294
 
32839 amit.gupta 295
    private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
296
                                    int catalogId, int itemQty) {
297
        if (monthlyPlanned == null) {
298
            monthlyPlanned = new MonthlyPlanned();
299
            monthlyPlanned.setFofoId(fofoId);
300
            monthlyPlanned.setYearMonth(currentMonthDate);
301
            monthlyPlannedRepository.persist(monthlyPlanned);
302
            PlannedDetail pd = new PlannedDetail();
303
            pd.setCatalogId(catalogId);
304
            pd.setPlannedId(monthlyPlanned.getId());
305
            pd.setQuantity(itemQty);
306
            pd.setUpdatedTimestamp(LocalDateTime.now());
307
            plannedDetailRepository.persist(pd);
25721 tejbeer 308
 
32839 amit.gupta 309
        } else {
310
            PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
311
                    catalogId);
312
            if (plannedDetail == null) {
313
                plannedDetail = new PlannedDetail();
314
                plannedDetail.setCatalogId(catalogId);
315
                plannedDetail.setPlannedId(monthlyPlanned.getId());
316
                plannedDetail.setQuantity(itemQty);
317
                plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
318
                plannedDetailRepository.persist(plannedDetail);
319
            } else if (itemQty == 0) {
320
                plannedDetailRepository.delete(plannedDetail);
25721 tejbeer 321
 
32839 amit.gupta 322
            } else {
323
                plannedDetail.setCatalogId(catalogId);
324
                plannedDetail.setQuantity(itemQty);
325
                plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
326
            }
25721 tejbeer 327
 
32839 amit.gupta 328
        }
25721 tejbeer 329
 
32839 amit.gupta 330
    }
25721 tejbeer 331
 
32839 amit.gupta 332
    @RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
333
    public String confirmOpenIndent(HttpServletRequest request,
334
                                    @RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {
26748 tejbeer 335
 
32839 amit.gupta 336
        if (fofoId == 0) {
337
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
338
            fofoId = loginDetails.getFofoId();
339
        }
340
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26748 tejbeer 341
 
32839 amit.gupta 342
        LocalDate currentDate = LocalDate.now();
343
        LocalDate planningMonthDate = null;
344
        MonthlyPlanned monthlyPlanned = null;
345
        if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {
346
            planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
347
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
25721 tejbeer 348
 
32839 amit.gupta 349
            confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
34952 ranu 350
        } else if (currentDate.isBefore(currentDate.withDayOfMonth(8))) {
351
            planningMonthDate = LocalDate.now().withDayOfMonth(1);
352
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
353
 
354
            confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
32839 amit.gupta 355
        }
356
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
26082 tejbeer 357
 
32839 amit.gupta 358
        return "response";
359
    }
26082 tejbeer 360
 
32839 amit.gupta 361
    private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
362
            throws Exception {
363
        List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
25721 tejbeer 364
 
32839 amit.gupta 365
        List<PlannedModel> plannedModel = new ArrayList<>();
366
        for (PlannedDetail plannedDetail : plannedDetails) {
25721 tejbeer 367
 
32839 amit.gupta 368
            List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
369
            String itemDesription = items.get(0).getItemDescriptionNoColor();
370
            PlannedModel pm = new PlannedModel();
371
            pm.setItemDescription(itemDesription);
372
            pm.setStoreName(customRetailer.getBusinessName());
373
            pm.setQty(plannedDetail.getQuantity());
374
            pm.setFofoId(fofoId);
375
            plannedModel.add(pm);
376
            LOGGER.info("plannedModel" + plannedModel);
25721 tejbeer 377
 
32839 amit.gupta 378
        }
379
        List<String> ccemails = new ArrayList<>();
380
        LOGGER.info("ccemails" + ccemails);
381
        Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);
382
        LOGGER.info("emailEsclationType" + emailEsclationType);
383
        if (emailEsclationType.get(EscalationType.L1) != null) {
384
            ccemails.add(emailEsclationType.get(EscalationType.L1));
385
        }
31636 tejbeer 386
 
32839 amit.gupta 387
        if (emailEsclationType.get(EscalationType.L2) != null) {
31636 tejbeer 388
 
32839 amit.gupta 389
            ccemails.add(emailEsclationType.get(EscalationType.L2));
390
        }
391
        LOGGER.info("ccemails" + ccemails);
392
        List<String> bccemails = new ArrayList<>();
393
        bccemails.add(emailEsclationType.get(EscalationType.L3));
394
        LOGGER.info("bccemails" + bccemails);
395
        ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
396
                Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
397
                plannedModel.stream()
398
                        .map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
399
                        .collect(Collectors.toList()));
400
        LOGGER.info("baos" + baos);
35957 amit 401
        mailOutboxService.queueMailWithAttachmentsViaGoogle(new String[]{customRetailer.getEmail()},
32839 amit.gupta 402
                ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),
35957 amit 403
                "Planned Indent", "PFA", false, "IndentController.confirmMonthlyPlanned",
404
                new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())));
25721 tejbeer 405
 
32839 amit.gupta 406
    }
23405 amit.gupta 407
 
32839 amit.gupta 408
    @RequestMapping(value = "/indent/download", method = RequestMethod.GET)
409
    public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
410
                                                            @RequestParam(required = false, defaultValue = "0") int fofoId,
411
                                                            @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
412
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
413
        Set<Integer> roleIds = loginDetails.getRoleIds();
414
        LOGGER.info("Counter size is {}", counterSize);
415
        LOGGER.info("Fofo Id is {}", fofoId);
30426 tejbeer 416
 
32839 amit.gupta 417
        if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
418
            List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
419
                    .collect(Collectors.toList());
420
            Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
421
            Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x))
422
                    .filter(x -> x != null).collect(Collectors.toList()).stream()
423
                    .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
424
            List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
425
                    true);
426
            Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
427
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 428
 
32839 amit.gupta 429
            Map<String, Integer> catalogUserQtyMap = new HashMap<>();
430
            currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
431
                int retailerId = x.getFofoId();
432
                int catalogId;
433
                try {
434
                    catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
435
                    String key = catalogId + "-" + retailerId;
436
                    if (!catalogUserQtyMap.containsKey(key)) {
437
                        catalogUserQtyMap.put(key, 0);
438
                    }
439
                    catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
440
                } catch (ProfitMandiBusinessException e) {
441
                    // TODO Auto-generated catch block
442
                    throw new RuntimeException(e);
443
                }
444
            });
23779 amit.gupta 445
 
32839 amit.gupta 446
            List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
447
            Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
448
                try {
449
                    return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
450
                            + x.getRetailerId();
451
                } catch (ProfitMandiBusinessException e) {
452
                    // TODO Auto-generated catch block
453
                    return "";
454
                }
455
            }, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 456
 
32839 amit.gupta 457
            Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
24232 amit.gupta 458
 
32839 amit.gupta 459
            List<TagListing> tagListings = tagListingRepository.selectAll(true);
460
            Iterator<TagListing> iterator = tagListings.iterator();
461
            while (iterator.hasNext()) {
462
                TagListing tagListing = iterator.next();
463
                Item item = itemRepository.selectById(tagListing.getItemId());
464
                int catalogId = item.getCatalogItemId();
465
                if (item.getCategoryId() != 10006) {
466
                    continue;
467
                }
23779 amit.gupta 468
 
32839 amit.gupta 469
                int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
470
                        ? modelStockAllocationMap.get(catalogId)
471
                        : 0;
472
                for (int retailerId : fofoIds) {
473
                    String key = catalogId + "-" + retailerId;
474
                    if (catalogListingMap.containsKey(key)) {
475
                        continue;
476
                    }
477
                    int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
478
                    int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
479
                    if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
480
                        continue;
481
                    }
482
                    CatalogListingModel catalogListingModel = new CatalogListingModel();
483
                    catalogListingModel.setFofoId(retailerId);
484
                    catalogListingModel.setModelName(item.getModelName());
485
                    catalogListingModel.setModelNumber(item.getModelNumber());
486
                    catalogListingModel.setCatalogId(catalogId);
487
                    catalogListingModel.setDp(tagListing.getSellingPrice());
488
                    catalogListingModel.setMop(tagListing.getMop());
489
                    catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
490
                    catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
491
                    catalogListingModel.setInTransitQuantity(catalogInTransit);
492
                    catalogListingModel
493
                            .setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
494
                    catalogListingModel.setStockInHand(catalogInStock);
495
                    catalogListingModel.setBrand(item.getBrand());
496
                    catalogListingModel.setModelName(item.getModelName());
497
                    catalogListingModel.setModelNumber(item.getModelNumber());
498
                    catalogListingModel.setCategoryId(item.getCategoryId());
499
                    catalogListingMap.put(key, catalogListingModel);
500
                }
501
            }
502
            List<List<?>> listOfRows = new ArrayList<>();
503
            for (CatalogListingModel clm : catalogListingMap.values()) {
504
                CustomRetailer cr = crm.get(clm.getFofoId());
505
                listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
506
                        clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
507
                        clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
508
                        clm.getToBeOrdered()));
509
            }
510
            ByteArrayOutputStream baos = FileUtil
511
                    .getCSVByteStream(
512
                            Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
513
                                    "DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
514
                            listOfRows);
515
            HttpHeaders headers = new HttpHeaders();
516
            headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
517
            headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
518
            return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
519
                    HttpStatus.OK);
520
        }
521
        return null;
24232 amit.gupta 522
 
32839 amit.gupta 523
    }
23405 amit.gupta 524
 
32839 amit.gupta 525
    @RequestMapping(value = "/itemsByCatalogId")
526
    public String getItemsByCatalogId(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("active",
543
                    tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
544
        });
545
        model.addAttribute("response1", response.toString());
546
        return "response";
24410 amit.gupta 547
 
32839 amit.gupta 548
    }
24349 amit.gupta 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);
35547 amit 574
        Set<Integer> updatedCatalogIds = new HashSet<>();
575
 
32839 amit.gupta 576
        for (int i = 0; i < jsonArray.length(); i++) {
577
            JSONObject obj = jsonArray.getJSONObject(i);
35547 amit 578
            int itemId = obj.getInt("id");
579
            TagListing tl = tagListingRepository.selectByItemId(itemId);
32839 amit.gupta 580
            if (tl == null) {
581
                continue;
582
            } else {
583
                tl.setActive(obj.getBoolean("active"));
584
                if (!tl.isActive()) {
585
                    saholicCISTableRepository.selectAllByItemId(tl.getItemId()).stream()
586
                            .forEach(x -> saholicCISTableRepository.delete(x));
587
                }
35547 amit 588
                // Collect catalogIds for Solr updates
589
                try {
590
                    Item item = itemRepository.selectById(itemId);
591
                    updatedCatalogIds.add(item.getCatalogItemId());
592
                } catch (Exception e) {
593
                    LOGGER.error("Failed to get catalogId for itemId: {}", itemId, e);
594
                }
32839 amit.gupta 595
            }
596
        }
35547 amit 597
 
598
        // Publish events for all updated catalogs
599
        for (Integer catalogId : updatedCatalogIds) {
600
            try {
601
                tagListingEventPublisher.publishStatusChange(0, catalogId);
602
            } catch (Exception e) {
603
                LOGGER.error("Failed to publish status change event for catalogId: {}", catalogId, e);
604
            }
605
        }
606
 
32839 amit.gupta 607
        model.addAttribute("response1", true);
608
        return "response";
609
    }
30664 amit.gupta 610
 
32839 amit.gupta 611
    @RequestMapping(value = "/indent/loadIndent")
612
    public String loadOpenIndent(HttpServletRequest request, Model model,
613
                                 @RequestParam(required = false, defaultValue = "0") int fofoId,
614
                                 @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 615
 
32839 amit.gupta 616
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
617
        Set<Integer> roleIds = loginDetails.getRoleIds();
618
        LOGGER.info("Counter size is {}", counterSize);
619
        LOGGER.info("Fofo Id is {}", fofoId);
620
        boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 621
 
34952 ranu 622
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
25797 tejbeer 623
 
32839 amit.gupta 624
        Map<String, Object> equalsMap = new HashMap<>();
625
        equalsMap.put("categoryId", 10006);
626
        equalsMap.put("brand", brands);
627
        Map<String, List<?>> notEqualsMap = new HashMap<>();
25796 tejbeer 628
 
32839 amit.gupta 629
        Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
630
        Map<Integer, Integer> currentStockMap;
25796 tejbeer 631
 
32839 amit.gupta 632
        if (!isAdmin && fofoId == 0) {
633
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
634
            Map<String, Object> equalsStockJoinMap = new HashMap<>();
635
            equalsStockJoinMap.put("fofoId", fofoId);
636
            currentStockMap = itemRepository
637
                    .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
638
                            equalsStockJoinMap, notEqualsJoinMap, "availability")
639
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
640
            LOGGER.info("currentStock");
641
        } else {
642
            if (fofoId == 0) {
25796 tejbeer 643
 
32839 amit.gupta 644
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
645
                equalsStockJoinMap.put("fofoId", fofoId);
25796 tejbeer 646
 
32839 amit.gupta 647
                currentStockMap = itemRepository
648
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
649
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
650
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25796 tejbeer 651
 
32839 amit.gupta 652
            } else {
25796 tejbeer 653
 
32839 amit.gupta 654
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
655
                equalsStockJoinMap.put("fofoId", fofoId);
25796 tejbeer 656
 
32839 amit.gupta 657
                currentStockMap = itemRepository
658
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
659
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
660
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25796 tejbeer 661
 
32839 amit.gupta 662
            }
663
        }
25796 tejbeer 664
 
32839 amit.gupta 665
        LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 666
 
32839 amit.gupta 667
        Map<Integer, Integer> itemsInTransit = null;
668
        List<TagListing> tagListings = tagListingRepository.selectAll(true);
669
        if (!isAdmin) {
670
            tagListings = new ArrayList<>(tagListings);
671
            List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
672
                    OrderRepository.validOrderStatusList);
673
            inTransitOrders = this.filterValidOrders(inTransitOrders);
674
            itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
675
                    Collectors.summingInt(x -> x.getLineItem().getQuantity())));
676
        } else {
677
            itemsInTransit = new HashMap<>();
678
        }
25797 tejbeer 679
 
32839 amit.gupta 680
        int totalPcs = 0;
25797 tejbeer 681
 
32839 amit.gupta 682
        float totalAmount = 0;
683
        Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
684
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
685
                .collect(Collectors.toList());
25796 tejbeer 686
 
32839 amit.gupta 687
        LOGGER.info("regionIds" + regionIds);
688
        Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
689
                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
690
        LOGGER.info("focusedModelMap" + focusedModelMap);
691
        LocalDate planningMonthDate = null;
692
        MonthlyPlanned monthlyPlanned = null;
693
        List<Integer> fofoOrderIds = null;
694
        LOGGER.info("localDate" + LocalDate.now());
695
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
696
            planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
697
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
698
            LOGGER.info("monthlyPlanned2" + monthlyPlanned);
699
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
700
                            LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
701
                    .collect(Collectors.toList());
702
            model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
34952 ranu 703
        } else if (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(8))) {
704
            planningMonthDate = LocalDate.now().withDayOfMonth(8);
705
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
706
            LOGGER.info("monthlyPlanned2" + monthlyPlanned);
707
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
708
                            LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
709
                    .collect(Collectors.toList());
710
            model.addAttribute("planningMonth", LocalDate.now().getMonth());
32839 amit.gupta 711
        } else {
712
            planningMonthDate = LocalDate.now().withDayOfMonth(1);
713
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
714
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
715
            model.addAttribute("planningMonth", planningMonthDate.getMonth());
716
            model.addAttribute("mtd", true);
717
            model.addAttribute("freezed", true);
718
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
719
                            curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
720
                    .collect(Collectors.toList());
721
            LOGGER.info("monthlyPlanned1" + monthlyPlanned);
722
        }
26082 tejbeer 723
 
32839 amit.gupta 724
        Map<Integer, Integer> plannedDetailMap = null;
725
        if (monthlyPlanned != null) {
726
            plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
727
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
25721 tejbeer 728
 
32839 amit.gupta 729
        }
730
        LOGGER.info("plannedDetailMap" + plannedDetailMap);
26176 tejbeer 731
 
32839 amit.gupta 732
        LOGGER.info("fofoOrderIds" + fofoOrderIds);
733
        Map<String, Object> equalsJoinMap = new HashMap<>();
26618 tejbeer 734
 
32839 amit.gupta 735
        equalsJoinMap.put("orderId", fofoOrderIds);
736
        Map<Integer, Integer> last15daysMap = null;
737
        if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
24231 amit.gupta 738
 
32839 amit.gupta 739
            last15daysMap = itemRepository
740
                    .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
741
                            notEqualsJoinMap, "quantity")
742
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
743
        }
744
        LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 745
 
32839 amit.gupta 746
        Map<Integer, TagListing> taglistingMap = tagListings.stream()
747
                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
748
        List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
749
        Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
750
                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
751
        LOGGER.info("catalogIdItemMap");
24231 amit.gupta 752
 
32839 amit.gupta 753
        Map<String, Object> equalsItemJoinMap = new HashMap<>();
754
        equalsItemJoinMap.put("active", 1);
755
        List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
756
                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
757
        LOGGER.info("tagListingCatalogIds");
758
        for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
759
            int catalogId = catalogIdAggregateValue.getCatalogId();
760
            Item item = catalogIdItemMap.get(catalogId).get(0);
761
            TagListing tagListing = taglistingMap.get(item.getId());
762
            CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
763
            if (!catalogListingMap.containsKey(catalogId)) {
764
                catalogListingModel = new CatalogListingModel();
765
                catalogListingModel.setCatalogId(catalogId);
766
                catalogListingModel.setDp(tagListing.getSellingPrice());
767
                catalogListingModel.setMop(tagListing.getMop());
768
                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
769
                if (plannedDetailMap != null) {
25721 tejbeer 770
 
32839 amit.gupta 771
                    Integer quantity = plannedDetailMap.get(catalogId);
772
                    if (quantity != null) {
773
                        catalogListingModel.setAllocatedQuantity(quantity);
774
                    }
775
                }
25721 tejbeer 776
 
32839 amit.gupta 777
                if (last15daysMap != null) {
778
                    Integer last15DaysSale = last15daysMap.get(catalogId);
25796 tejbeer 779
 
32839 amit.gupta 780
                    if (last15DaysSale != null) {
781
                        catalogListingModel.setLast15DaysSale(last15DaysSale);
782
                    } else {
783
                        catalogListingModel.setLast15DaysSale(0);
784
                    }
785
                } else {
786
                    catalogListingModel.setLast15DaysSale(0);
787
                }
25721 tejbeer 788
 
32839 amit.gupta 789
                catalogListingModel.setBrand(item.getBrand());
790
                if (item.getCategoryId() == 10006) {
791
                    catalogListingModel.setCategoryId(item.getCategoryId());
792
                }
25721 tejbeer 793
 
32839 amit.gupta 794
                FocusedModel fm = focusedModelMap.get(catalogId);
795
                if (fm != null) {
796
                    catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
797
                    catalogListingModel.setMinimumQty(fm.getMinimumQty());
25721 tejbeer 798
 
32839 amit.gupta 799
                } else {
800
                    catalogListingModel.setRecommendedQty(0);
801
                    catalogListingModel.setMinimumQty(0);
802
                }
25721 tejbeer 803
 
32839 amit.gupta 804
                catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 805
 
32839 amit.gupta 806
            }
807
            int itemAvailability = 0;
808
            if (currentStockMap != null) {
809
                Integer qty = currentStockMap.get(catalogId);
810
                itemAvailability = qty == null ? 0 : qty;
811
                catalogListingModel.setStockInHand(itemAvailability);
812
            } else {
813
                catalogListingModel.setStockInHand(0);
814
            }
815
            Integer inTransitQuantity = itemsInTransit.get(item.getId());
816
            int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
817
            catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
818
            if (plannedDetailMap != null) {
819
                if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 820
 
32839 amit.gupta 821
                    int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
822
                            + catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
823
                    LOGGER.info("remaning" + remaining);
26176 tejbeer 824
 
32839 amit.gupta 825
                    if (remaining != 0) {
826
                        catalogListingModel.setRemaining(remaining);
827
                    } else {
828
                        catalogListingModel.setRemaining(0);
829
                    }
830
                }
831
            }
832
        }
25721 tejbeer 833
 
32839 amit.gupta 834
        Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
835
        if (fofoId > 0) {
836
            CustomRetailer customRetailer = customRetailersMap.get(fofoId);
837
            model.addAttribute("retailerName",
838
                    customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
839
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
840
            model.addAttribute("retailerId", customRetailer.getPartnerId());
841
            model.addAttribute("counterSize", fs.getCounterSize().toString());
842
        } else {
843
            model.addAttribute("counterSize", counterSize.toString());
844
        }
845
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 846
 
32839 amit.gupta 847
        List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
25702 amit.gupta 848
 
32839 amit.gupta 849
        Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
850
                Comparator.reverseOrder());
851
        LOGGER.info("monthlyPlanned" + monthlyPlanned);
852
        model.addAttribute("catalogTagListings",
853
                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
854
        model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
855
        model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
856
        model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
857
        model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());
26131 tejbeer 858
 
32839 amit.gupta 859
        model.addAttribute("customRetailers", customRetailers);
860
        model.addAttribute("totalAmount", totalAmount);
861
        model.addAttribute("monthlyPlanned", monthlyPlanned);
862
        model.addAttribute("totalPcs", totalPcs);
863
        return "open-indent";
25796 tejbeer 864
 
32839 amit.gupta 865
    }
23796 amit.gupta 866
 
32839 amit.gupta 867
    @RequestMapping(value = "/indent/loadIndentPreviousMonth")
868
    public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
869
                                              @RequestParam(required = false, defaultValue = "0") int fofoId,
870
                                              @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
871
        LocalDate planMonthStart = null;
872
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
873
            planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
874
        } else {
875
            planMonthStart = LocalDate.now().withDayOfMonth(1);
876
        }
877
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
878
        Set<Integer> roleIds = loginDetails.getRoleIds();
879
        LOGGER.info("Counter size is {}", counterSize);
880
        LOGGER.info("Fofo Id is {}", fofoId);
881
        boolean isAdmin = roleManager.isAdmin(roleIds);
26131 tejbeer 882
 
34952 ranu 883
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
26131 tejbeer 884
 
32839 amit.gupta 885
        Map<String, Object> equalsMap = new HashMap<>();
886
        equalsMap.put("categoryId", 10006);
887
        equalsMap.put("brand", brands);
888
        Map<String, List<?>> notEqualsMap = new HashMap<>();
26131 tejbeer 889
 
32839 amit.gupta 890
        Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
891
        Map<Integer, Integer> currentStockMap;
26131 tejbeer 892
 
32839 amit.gupta 893
        if (!isAdmin && fofoId == 0) {
894
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
895
            Map<String, Object> equalsStockJoinMap = new HashMap<>();
896
            equalsStockJoinMap.put("fofoId", fofoId);
897
            currentStockMap = itemRepository
898
                    .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
899
                            equalsStockJoinMap, notEqualsJoinMap, "availability")
900
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
901
            LOGGER.info("currentStock");
902
        } else {
903
            if (fofoId == 0) {
26131 tejbeer 904
 
32839 amit.gupta 905
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
906
                equalsStockJoinMap.put("fofoId", fofoId);
26131 tejbeer 907
 
32839 amit.gupta 908
                currentStockMap = itemRepository
909
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
910
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
911
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26131 tejbeer 912
 
32839 amit.gupta 913
            } else {
26131 tejbeer 914
 
32839 amit.gupta 915
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
916
                equalsStockJoinMap.put("fofoId", fofoId);
26131 tejbeer 917
 
32839 amit.gupta 918
                currentStockMap = itemRepository
919
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
920
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
921
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26131 tejbeer 922
 
32839 amit.gupta 923
            }
924
        }
26131 tejbeer 925
 
32839 amit.gupta 926
        LOGGER.info("currentStock" + currentStockMap);
26131 tejbeer 927
 
32839 amit.gupta 928
        Map<Integer, Integer> itemsInTransit = null;
929
        List<TagListing> tagListings = tagListingRepository.selectAll(true);
930
        if (!isAdmin) {
931
            tagListings = new ArrayList<>(tagListings);
932
            List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
933
                    OrderRepository.validOrderStatusList);
934
            inTransitOrders = this.filterValidOrders(inTransitOrders);
935
            itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
936
                    Collectors.summingInt(x -> x.getLineItem().getQuantity())));
937
        } else {
938
            itemsInTransit = new HashMap<>();
939
        }
26131 tejbeer 940
 
32839 amit.gupta 941
        int totalPcs = 0;
26131 tejbeer 942
 
32839 amit.gupta 943
        float totalAmount = 0;
944
        Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
26131 tejbeer 945
 
32839 amit.gupta 946
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
947
                .collect(Collectors.toList());
26131 tejbeer 948
 
32839 amit.gupta 949
        Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
950
                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
27088 tejbeer 951
 
32839 amit.gupta 952
        MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
953
                planMonthStart.minusMonths(1));
954
        model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
955
        model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
956
        model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 957
 
32839 amit.gupta 958
        Map<Integer, Integer> plannedDetailMap = null;
959
        if (monthlyPlanned != null) {
960
            plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
961
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
26131 tejbeer 962
 
32839 amit.gupta 963
        }
26131 tejbeer 964
 
32839 amit.gupta 965
        LOGGER.info("plannedDetailMap" + plannedDetailMap);
966
        List<Integer> fofoOrderIds = fofoOrderRepository
967
                .selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
968
                        planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
969
                .stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 970
 
32839 amit.gupta 971
        LOGGER.info("fofoOrderIds" + fofoOrderIds);
972
        Map<String, Object> equalsJoinMap = new HashMap<>();
973
        equalsJoinMap.put("orderId", fofoOrderIds);
974
        Map<Integer, Integer> lastMonthSaleMap = null;
975
        if (!fofoOrderIds.isEmpty()) {
976
            lastMonthSaleMap = itemRepository
977
                    .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
978
                            notEqualsJoinMap, "quantity")
979
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
980
        }
981
        LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
26131 tejbeer 982
 
32839 amit.gupta 983
        Map<Integer, TagListing> taglistingMap = tagListings.stream()
984
                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
985
        List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
986
        Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
987
                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
988
        LOGGER.info("catalogIdItemMap");
26131 tejbeer 989
 
32839 amit.gupta 990
        Map<String, Object> equalsItemJoinMap = new HashMap<>();
991
        equalsItemJoinMap.put("active", 1);
992
        List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
993
                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
994
        LOGGER.info("tagListingCatalogIds");
995
        for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
996
            int catalogId = catalogIdAggregateValue.getCatalogId();
997
            Item item = catalogIdItemMap.get(catalogId).get(0);
998
            TagListing tagListing = taglistingMap.get(item.getId());
999
            CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1000
            if (!catalogListingMap.containsKey(catalogId)) {
1001
                catalogListingModel = new CatalogListingModel();
1002
                catalogListingModel.setCatalogId(catalogId);
1003
                catalogListingModel.setDp(tagListing.getSellingPrice());
1004
                catalogListingModel.setMop(tagListing.getMop());
1005
                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1006
                if (plannedDetailMap != null) {
26131 tejbeer 1007
 
32839 amit.gupta 1008
                    Integer quantity = plannedDetailMap.get(catalogId);
1009
                    if (quantity != null) {
1010
                        catalogListingModel.setAllocatedQuantity(quantity);
1011
                    }
1012
                }
26131 tejbeer 1013
 
32839 amit.gupta 1014
                if (lastMonthSaleMap != null) {
1015
                    Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
26131 tejbeer 1016
 
32839 amit.gupta 1017
                    if (lastMonthSale != null) {
1018
                        catalogListingModel.setLastMonthSaleMap(lastMonthSale);
1019
                    } else {
1020
                        catalogListingModel.setLastMonthSaleMap(0);
1021
                    }
1022
                } else {
1023
                    catalogListingModel.setLast15DaysSale(0);
1024
                }
26131 tejbeer 1025
 
32839 amit.gupta 1026
                catalogListingModel.setBrand(item.getBrand());
1027
                if (item.getCategoryId() == 10006) {
1028
                    catalogListingModel.setCategoryId(item.getCategoryId());
1029
                }
26131 tejbeer 1030
 
32839 amit.gupta 1031
                FocusedModel fm = focusedModelMap.get(catalogId);
1032
                if (fm != null) {
1033
                    catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1034
                    catalogListingModel.setMinimumQty(fm.getMinimumQty());
26131 tejbeer 1035
 
32839 amit.gupta 1036
                } else {
1037
                    catalogListingModel.setRecommendedQty(0);
1038
                    catalogListingModel.setMinimumQty(0);
1039
                }
26131 tejbeer 1040
 
32839 amit.gupta 1041
                catalogListingMap.put(catalogId, catalogListingModel);
26131 tejbeer 1042
 
32839 amit.gupta 1043
            }
1044
            int itemAvailability = 0;
1045
            if (currentStockMap != null) {
1046
                Integer qty = currentStockMap.get(catalogId);
1047
                itemAvailability = qty == null ? 0 : qty;
1048
                catalogListingModel.setStockInHand(itemAvailability);
1049
            } else {
1050
                catalogListingModel.setStockInHand(0);
1051
            }
1052
            Integer inTransitQuantity = itemsInTransit.get(item.getId());
1053
            int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1054
            catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26131 tejbeer 1055
 
32839 amit.gupta 1056
        }
26131 tejbeer 1057
 
32839 amit.gupta 1058
        Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
1059
        if (fofoId > 0) {
1060
            CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1061
            model.addAttribute("retailerName",
1062
                    customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1063
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1064
            model.addAttribute("retailerId", customRetailer.getPartnerId());
1065
            model.addAttribute("counterSize", fs.getCounterSize().toString());
1066
        } else {
1067
            model.addAttribute("counterSize", counterSize.toString());
1068
        }
1069
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
26131 tejbeer 1070
 
32839 amit.gupta 1071
        List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
26131 tejbeer 1072
 
32839 amit.gupta 1073
        Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1074
                Comparator.reverseOrder());
1075
        LOGGER.info("monthlyPlanned" + monthlyPlanned);
1076
        model.addAttribute("catalogTagListings",
1077
                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1078
        model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1079
        model.addAttribute("previousMonth", true);
1080
        model.addAttribute("freezed", true);
1081
        model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
1082
        model.addAttribute("customRetailers", customRetailers);
1083
        model.addAttribute("totalAmount", totalAmount);
1084
        model.addAttribute("monthlyPlanned", monthlyPlanned);
1085
        model.addAttribute("totalPcs", totalPcs);
1086
        return "open-indent";
26131 tejbeer 1087
 
32839 amit.gupta 1088
    }
26131 tejbeer 1089
 
32839 amit.gupta 1090
    private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1091
        Map<Integer, Item> itemMap = new HashMap<>();
1092
        for (FocusedModel focusedModel : focusedModels) {
1093
            List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1094
            itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
1095
        }
23796 amit.gupta 1096
 
32839 amit.gupta 1097
        return itemMap;
1098
    }
25378 tejbeer 1099
 
32839 amit.gupta 1100
    private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
1101
        Map<Integer, Region> regionMap = new HashMap<>();
1102
        for (FocusedModel focusedModel : focusedModels) {
1103
            Region region = regionRepository.selectById(focusedModel.getRegionId());
1104
            regionMap.put(region.getId(), region);
1105
        }
24231 amit.gupta 1106
 
32839 amit.gupta 1107
        return regionMap;
1108
    }
24231 amit.gupta 1109
 
32839 amit.gupta 1110
    @RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1111
    public String getFocusedModel(HttpServletRequest request,
1112
                                  @RequestParam(name = "offset", defaultValue = "0") int offset,
33412 ranu 1113
                                  @RequestParam(name = "limit", defaultValue = "0") int limit, Model model)
32839 amit.gupta 1114
            throws ProfitMandiBusinessException {
25736 tejbeer 1115
 
32839 amit.gupta 1116
        long size = 0;
1117
        List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
33412 ranu 1118
        Collections.reverse(focusedModels);
32839 amit.gupta 1119
        size = focusedModelRepository.selectAllCount();
1120
        if (!focusedModels.isEmpty()) {
1121
            Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
1122
            Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25721 tejbeer 1123
 
32839 amit.gupta 1124
            LOGGER.info("regionMap" + regionMap);
1125
            model.addAttribute("focusedModels", focusedModels);
1126
            model.addAttribute("itemMap", itemMap);
1127
            model.addAttribute("regionMap", regionMap);
1128
            model.addAttribute("start", offset + 1);
1129
            model.addAttribute("size", size);
1130
            model.addAttribute("url", "/getPaginatedFocusedModel");
25736 tejbeer 1131
 
32839 amit.gupta 1132
            if (focusedModels.size() < limit) {
1133
                model.addAttribute("end", offset + focusedModels.size());
1134
            } else {
1135
                model.addAttribute("end", offset + limit);
1136
            }
1137
        } else {
32170 jai.hind 1138
 
32839 amit.gupta 1139
            model.addAttribute("walletRequest", focusedModels);
1140
            model.addAttribute("size", size);
32171 jai.hind 1141
 
32839 amit.gupta 1142
        }
25736 tejbeer 1143
 
32839 amit.gupta 1144
        List<Region> regions = regionRepository.selectAll();
27081 tejbeer 1145
 
32839 amit.gupta 1146
        model.addAttribute("regions", regions);
27088 tejbeer 1147
 
32839 amit.gupta 1148
        return "focused_model";
1149
    }
25721 tejbeer 1150
 
32839 amit.gupta 1151
    @RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1152
    public String getPaginatedFocusedModel(HttpServletRequest request,
1153
                                           @RequestParam(name = "offset", defaultValue = "0") int offset,
1154
                                           @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1155
            throws ProfitMandiBusinessException {
1156
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1157
        List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
25736 tejbeer 1158
 
32839 amit.gupta 1159
        if (!focusedModels.isEmpty()) {
1160
            Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
1161
            Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
1162
            model.addAttribute("focusedModels", focusedModels);
1163
            model.addAttribute("itemMap", itemMap);
1164
            model.addAttribute("regionMap", regionMap);
1165
            model.addAttribute("url", "/getPaginatedFocusedModel");
1166
        } else {
1167
            model.addAttribute("focusedModels", focusedModels);
25736 tejbeer 1168
 
32839 amit.gupta 1169
        }
27081 tejbeer 1170
 
32839 amit.gupta 1171
        List<Region> regions = regionRepository.selectAll();
27088 tejbeer 1172
 
32839 amit.gupta 1173
        model.addAttribute("regions", regions);
1174
        return "focused-model-paginated";
1175
    }
25736 tejbeer 1176
 
32839 amit.gupta 1177
    private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1178
        Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1179
 
35236 amit 1180
        List<BrandCatalog> mobileBrands = brandsService.getBrands(fofoId, null, 3);
32839 amit.gupta 1181
        List<BrandStockPrice> brandStockPrices = new ArrayList<>();
25798 tejbeer 1182
 
32839 amit.gupta 1183
        mobileBrands.stream().forEach(x -> {
35236 amit 1184
            String brand = x.getName();
32839 amit.gupta 1185
            if (brandStockPricesMap.containsKey(brand)) {
1186
                BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
35236 amit 1187
                brandStockPrice.setBrandUrl(x.getLogoUrl());
1188
                brandStockPrice.setRank(x.getBrandCategory().getRank());
32839 amit.gupta 1189
                brandStockPrices.add(brandStockPrice);
1190
            }
1191
        });
25798 tejbeer 1192
 
32839 amit.gupta 1193
        return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1194
                .collect(Collectors.toList());
1195
    }
25798 tejbeer 1196
 
32839 amit.gupta 1197
    @RequestMapping(value = "/getPartnerAllocation")
1198
    public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
26721 tejbeer 1199
 
32839 amit.gupta 1200
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1201
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
26721 tejbeer 1202
 
32839 amit.gupta 1203
        Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26721 tejbeer 1204
 
32839 amit.gupta 1205
        List<Integer> fofoIds = pp.get(authUser.getId());
26721 tejbeer 1206
 
32839 amit.gupta 1207
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1208
        Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1209
                .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1210
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1211
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
26721 tejbeer 1212
 
32839 amit.gupta 1213
        model.addAttribute("customRetailersMap", crm);
1214
        model.addAttribute("fofoStoreMap", fofoStoreMap);
1215
        return "partners_allocation";
26721 tejbeer 1216
 
32839 amit.gupta 1217
    }
26721 tejbeer 1218
 
32839 amit.gupta 1219
    @RequestMapping(value = "/partnerPendingOrder")
1220
    public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1221
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1222
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
26846 tejbeer 1223
 
32839 amit.gupta 1224
        Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26846 tejbeer 1225
 
32839 amit.gupta 1226
        List<Integer> fofoIds = pp.get(authUser.getId());
1227
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1228
        Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1229
                .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
26846 tejbeer 1230
 
32839 amit.gupta 1231
        model.addAttribute("customRetailersMap", crm);
26846 tejbeer 1232
 
32839 amit.gupta 1233
        return "partner-po";
26846 tejbeer 1234
 
32839 amit.gupta 1235
    }
26846 tejbeer 1236
 
32839 amit.gupta 1237
    @RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1238
    public String focusedModel(HttpServletRequest request, @RequestParam int catalogId,
1239
                               @RequestParam(name = "recommended", defaultValue = "0") int recommended,
1240
                               @RequestParam(name = "minimumQty", defaultValue = "0") int minimumQty,
1241
                               @RequestParam(name = "obvrecommend", defaultValue = "0") int obvrecommend,
1242
                               @RequestParam(name = "obvminimum", defaultValue = "0") int obvminimum, @RequestParam int regionId,
1243
                               Model model) throws ProfitMandiBusinessException {
30664 amit.gupta 1244
 
32839 amit.gupta 1245
        FocusedModel fm = new FocusedModel();
1246
        fm.setCatalogId(catalogId);
1247
        fm.setMinimumQty(minimumQty);
1248
        fm.setRecommendedQty(recommended);
1249
        fm.setRegionId(regionId);
1250
        fm.setObsRecommendedQty(obvrecommend);
1251
        fm.setObsMinimumQty(obvminimum);
1252
        fm.setCreatedTimestamp(LocalDateTime.now());
1253
        focusedModelRepository.persist(fm);
1254
        return "focused_model";
1255
    }
30664 amit.gupta 1256
 
32839 amit.gupta 1257
    @RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1258
    public String removeFocusedModelItem(HttpServletRequest request,
1259
                                         @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
30017 amit.gupta 1260
 
32839 amit.gupta 1261
        focusedModelRepository.deleteById(id);
1262
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1263
        return "response";
1264
    }
30017 amit.gupta 1265
 
32839 amit.gupta 1266
    @RequestMapping(value = "/getPartnerloadContent")
1267
    public String getPartnerloadContent(HttpServletRequest request, Model model,
1268
                                        @RequestParam(required = false, defaultValue = "0") int fofoId,
1269
                                        @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26846 tejbeer 1270
 
32839 amit.gupta 1271
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1272
        Set<Integer> roleIds = loginDetails.getRoleIds();
1273
        LOGGER.info("Counter size is {}", counterSize);
1274
        LOGGER.info("Fofo Id is {}", fofoId);
1275
        boolean isAdmin = roleManager.isAdmin(roleIds);
26846 tejbeer 1276
 
34952 ranu 1277
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
26846 tejbeer 1278
 
32839 amit.gupta 1279
        Map<String, Object> equalsMap = new HashMap<>();
1280
        equalsMap.put("categoryId", 10006);
1281
        equalsMap.put("brand", brands);
1282
        Map<String, List<?>> notEqualsMap = new HashMap<>();
26846 tejbeer 1283
 
32839 amit.gupta 1284
        Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1285
        Map<Integer, Integer> currentStockMap;
26846 tejbeer 1286
 
32839 amit.gupta 1287
        if (!isAdmin && fofoId == 0) {
1288
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1289
            Map<String, Object> equalsStockJoinMap = new HashMap<>();
1290
            equalsStockJoinMap.put("fofoId", fofoId);
1291
            currentStockMap = itemRepository
1292
                    .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1293
                            equalsStockJoinMap, notEqualsJoinMap, "availability")
1294
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1295
            LOGGER.info("currentStock");
1296
        } else {
1297
            if (fofoId == 0) {
26846 tejbeer 1298
 
32839 amit.gupta 1299
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
1300
                equalsStockJoinMap.put("fofoId", fofoId);
26846 tejbeer 1301
 
32839 amit.gupta 1302
                currentStockMap = itemRepository
1303
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1304
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
1305
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26846 tejbeer 1306
 
32839 amit.gupta 1307
            } else {
26846 tejbeer 1308
 
32839 amit.gupta 1309
                Map<String, Object> equalsStockJoinMap = new HashMap<>();
1310
                equalsStockJoinMap.put("fofoId", fofoId);
26846 tejbeer 1311
 
32839 amit.gupta 1312
                currentStockMap = itemRepository
1313
                        .selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1314
                                equalsStockJoinMap, notEqualsJoinMap, "availability")
1315
                        .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
26846 tejbeer 1316
 
32839 amit.gupta 1317
            }
1318
        }
26846 tejbeer 1319
 
32839 amit.gupta 1320
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
1321
        LOGGER.info("currentStock" + currentStockMap);
26846 tejbeer 1322
 
32839 amit.gupta 1323
        Map<Integer, Integer> itemsInTransit = null;
1324
        List<TagListing> tagListings = tagListingRepository.selectAll(true);
1325
        if (!isAdmin) {
1326
            tagListings = new ArrayList<>(tagListings);
1327
            List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
1328
                    OrderRepository.validOrderStatusList);
1329
            inTransitOrders = this.filterValidOrders(inTransitOrders);
1330
            itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1331
                    Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1332
        } else {
1333
            itemsInTransit = new HashMap<>();
1334
        }
26846 tejbeer 1335
 
32839 amit.gupta 1336
        int totalPcs = 0;
26846 tejbeer 1337
 
32839 amit.gupta 1338
        float totalAmount = 0;
1339
        Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
26846 tejbeer 1340
 
32839 amit.gupta 1341
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1342
                .collect(Collectors.toList());
26846 tejbeer 1343
 
32839 amit.gupta 1344
        Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1345
                .collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
27088 tejbeer 1346
 
32839 amit.gupta 1347
        LocalDate currentMonthDate = LocalDate.now();
1348
        MonthlyPlanned monthlyPlanned = null;
1349
        List<Integer> fofoOrderIds = null;
1350
        LOGGER.info("localDate" + LocalDate.now());
1351
        if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
1352
            currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1353
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1354
            LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1355
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1356
                            LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
1357
                    .collect(Collectors.toList());
26846 tejbeer 1358
 
32839 amit.gupta 1359
            model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
1360
        } else {
1361
            currentMonthDate = LocalDate.now().withDayOfMonth(1);
1362
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
1363
            monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1364
            model.addAttribute("planningMonth", currentMonthDate.getMonth());
1365
            model.addAttribute("mtd", true);
1366
            model.addAttribute("freezed", true);
1367
            fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1368
                            curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
1369
                    .collect(Collectors.toList());
1370
            LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1371
        }
26846 tejbeer 1372
 
32839 amit.gupta 1373
        Map<Integer, Integer> plannedDetailMap = null;
1374
        if (monthlyPlanned != null) {
1375
            plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1376
                    .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
26846 tejbeer 1377
 
32839 amit.gupta 1378
        }
1379
        LOGGER.info("plannedDetailMap" + plannedDetailMap);
26846 tejbeer 1380
 
32839 amit.gupta 1381
        LOGGER.info("fofoOrderIds" + fofoOrderIds);
1382
        Map<String, Object> equalsJoinMap = new HashMap<>();
26846 tejbeer 1383
 
32839 amit.gupta 1384
        equalsJoinMap.put("orderId", fofoOrderIds);
1385
        Map<Integer, Integer> last15daysMap = null;
1386
        if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
26846 tejbeer 1387
 
32839 amit.gupta 1388
            last15daysMap = itemRepository
1389
                    .selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1390
                            notEqualsJoinMap, "quantity")
1391
                    .stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1392
        }
1393
        LOGGER.info("last15daysMap" + last15daysMap);
26846 tejbeer 1394
 
32839 amit.gupta 1395
        Map<Integer, TagListing> taglistingMap = tagListings.stream()
1396
                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1397
        List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1398
        Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1399
                Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1400
        LOGGER.info("catalogIdItemMap");
26846 tejbeer 1401
 
32839 amit.gupta 1402
        Map<String, Object> equalsItemJoinMap = new HashMap<>();
1403
        equalsItemJoinMap.put("active", 1);
1404
        List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
1405
                "itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
1406
        Map<Integer, Integer> ourStockAvailability = new HashMap<>();
27768 tejbeer 1407
 
32839 amit.gupta 1408
        Map<Integer, List<Integer>> catalogItemIdMap = itemRepository
1409
                .selectAllByCatalogIds(new HashSet<>(
1410
                        tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList())))
1411
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1412
                        Collectors.mapping(y -> y.getId(), Collectors.toList())));
1413
        for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {
1414
            List<Integer> itemIds = catalogItem.getValue();
1415
            int availability = 0;
1416
            for (Integer itemId : itemIds) {
1417
                List<SaholicCISTable> saholicCISTableList = saholicCISTableRepository.selectByItemWarehouse(itemId,
1418
                        fofoStore.getWarehouseId());
1419
                if (saholicCISTableList != null) {
1420
                    availability += saholicCISTableList.stream()
1421
                            .collect(Collectors.summingInt(x -> x.getAvailability()));
1422
                }
1423
            }
1424
            Integer catalogItemId = catalogItem.getKey();
1425
            ourStockAvailability.put(catalogItemId, availability);
1426
        }
1427
        LOGGER.info("ourStockAvailability" + ourStockAvailability);
27768 tejbeer 1428
 
32839 amit.gupta 1429
        for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
1430
            int catalogId = catalogIdAggregateValue.getCatalogId();
1431
            Item item = catalogIdItemMap.get(catalogId).get(0);
1432
            TagListing tagListing = taglistingMap.get(item.getId());
1433
            CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1434
            if (!catalogListingMap.containsKey(catalogId)) {
1435
                catalogListingModel = new CatalogListingModel();
1436
                catalogListingModel.setCatalogId(catalogId);
1437
                catalogListingModel.setDp(tagListing.getSellingPrice());
1438
                catalogListingModel.setMop(tagListing.getMop());
1439
                catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1440
                if (plannedDetailMap != null) {
26846 tejbeer 1441
 
32839 amit.gupta 1442
                    Integer quantity = plannedDetailMap.get(catalogId);
1443
                    if (quantity != null) {
1444
                        catalogListingModel.setAllocatedQuantity(quantity);
1445
                    }
1446
                }
26846 tejbeer 1447
 
32839 amit.gupta 1448
                if (last15daysMap != null) {
1449
                    Integer last15DaysSale = last15daysMap.get(catalogId);
26846 tejbeer 1450
 
32839 amit.gupta 1451
                    if (last15DaysSale != null) {
1452
                        catalogListingModel.setLast15DaysSale(last15DaysSale);
1453
                    } else {
1454
                        catalogListingModel.setLast15DaysSale(0);
1455
                    }
1456
                } else {
1457
                    catalogListingModel.setLast15DaysSale(0);
1458
                }
26846 tejbeer 1459
 
32839 amit.gupta 1460
                catalogListingModel.setBrand(item.getBrand());
1461
                if (item.getCategoryId() == 10006) {
1462
                    catalogListingModel.setCategoryId(item.getCategoryId());
1463
                }
26846 tejbeer 1464
 
32839 amit.gupta 1465
                Integer ourStock = ourStockAvailability.get(catalogId);
1466
                LOGGER.info("catalogId" + catalogId);
27768 tejbeer 1467
 
32839 amit.gupta 1468
                LOGGER.info("ourStock" + ourStock);
1469
                if (ourStock != null) {
1470
                    catalogListingModel.setOurStockQty(ourStock);
1471
                }
27768 tejbeer 1472
 
32839 amit.gupta 1473
                FocusedModel fm = focusedModelMap.get(catalogId);
1474
                if (fm != null) {
1475
                    catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1476
                    catalogListingModel.setMinimumQty(fm.getMinimumQty());
1477
                    catalogListingModel.setObsRecommendedQty(fm.getObsRecommendedQty());
1478
                    catalogListingModel.setObsMinimumQty(fm.getObsMinimumQty());
26846 tejbeer 1479
 
32839 amit.gupta 1480
                } else {
1481
                    catalogListingModel.setRecommendedQty(0);
1482
                    catalogListingModel.setMinimumQty(0);
29667 tejbeer 1483
 
32839 amit.gupta 1484
                    catalogListingModel.setObsRecommendedQty(0);
1485
                    catalogListingModel.setObsMinimumQty(0);
29667 tejbeer 1486
 
32839 amit.gupta 1487
                }
26846 tejbeer 1488
 
32839 amit.gupta 1489
                catalogListingMap.put(catalogId, catalogListingModel);
26846 tejbeer 1490
 
32839 amit.gupta 1491
            }
1492
            int itemAvailability = 0;
1493
            if (currentStockMap != null) {
1494
                Integer qty = currentStockMap.get(catalogId);
1495
                itemAvailability = qty == null ? 0 : qty;
1496
                catalogListingModel.setStockInHand(itemAvailability);
1497
            } else {
1498
                catalogListingModel.setStockInHand(0);
1499
            }
1500
            Integer inTransitQuantity = itemsInTransit.get(item.getId());
1501
            int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1502
            catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1503
            if (plannedDetailMap != null) {
1504
                if (plannedDetailMap.get(catalogId) != null) {
26846 tejbeer 1505
 
32839 amit.gupta 1506
                    int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1507
                            + catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1508
                    LOGGER.info("remaning" + remaining);
26846 tejbeer 1509
 
32839 amit.gupta 1510
                    if (remaining != 0) {
1511
                        catalogListingModel.setRemaining(remaining);
1512
                    } else {
1513
                        catalogListingModel.setRemaining(0);
1514
                    }
1515
                }
1516
            }
1517
        }
26846 tejbeer 1518
 
32839 amit.gupta 1519
        Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
1520
        if (fofoId > 0) {
1521
            CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1522
            model.addAttribute("retailerName",
1523
                    customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1524
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1525
            model.addAttribute("retailerId", customRetailer.getPartnerId());
1526
            model.addAttribute("counterSize", fs.getCounterSize().toString());
1527
        } else {
1528
            model.addAttribute("counterSize", counterSize.toString());
1529
        }
1530
        String customRetailers = JSONObject.valueToString(customRetailersMap.values());
26846 tejbeer 1531
 
32839 amit.gupta 1532
        List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
26846 tejbeer 1533
 
32839 amit.gupta 1534
        Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1535
                Comparator.reverseOrder());
1536
        LOGGER.info("monthlyPlanned" + monthlyPlanned);
1537
        model.addAttribute("catalogTagListings",
1538
                catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1539
        model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1540
        model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
1541
        model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1542
        model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
26846 tejbeer 1543
 
32839 amit.gupta 1544
        model.addAttribute("customRetailers", customRetailers);
1545
        model.addAttribute("totalAmount", totalAmount);
1546
        model.addAttribute("monthlyPlanned", monthlyPlanned);
1547
        model.addAttribute("totalPcs", totalPcs);
26846 tejbeer 1548
 
32839 amit.gupta 1549
        UserWallet userWallet = walletService.getUserWallet(fofoId);
26846 tejbeer 1550
 
32839 amit.gupta 1551
        model.addAttribute("userWallet", userWallet);
26846 tejbeer 1552
 
32839 amit.gupta 1553
        return "create-partner-po";
26846 tejbeer 1554
 
32839 amit.gupta 1555
    }
26846 tejbeer 1556
 
32839 amit.gupta 1557
    @RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1558
    public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1559
            throws Exception {
26846 tejbeer 1560
 
32839 amit.gupta 1561
        List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
26846 tejbeer 1562
 
32839 amit.gupta 1563
        List<Item> items = new ArrayList<>();
1564
        for (Item item : selecteditems) {
26846 tejbeer 1565
 
32839 amit.gupta 1566
            TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
26846 tejbeer 1567
 
32839 amit.gupta 1568
            if (tagListing != null) {
1569
                items.add(item);
1570
            }
26846 tejbeer 1571
 
32839 amit.gupta 1572
        }
1573
        model.addAttribute("items", items);
1574
        LOGGER.info("itemIdAndColorMap" + items);
1575
        return "select-item-color";
1576
    }
26846 tejbeer 1577
 
32839 amit.gupta 1578
    List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
34211 vikas.jang 1579
            "niranjan.kala@smartdukaan.com", "amit.gupta@smartdukaan.com", "vikas.jangra@smartdukaan.com");
30003 tejbeer 1580
 
32839 amit.gupta 1581
    @Autowired
1582
    private PositionRepository positionRepository;
30003 tejbeer 1583
 
32839 amit.gupta 1584
    @Autowired
1585
    private PartnerTypeChangeService partnerTypeChangeService;
30003 tejbeer 1586
 
32839 amit.gupta 1587
    @Autowired
1588
    private com.spice.profitmandi.service.transaction.TransactionService transactionService;
30003 tejbeer 1589
 
32839 amit.gupta 1590
    @Autowired
1591
    private CategoryRepository categoryRepository;
30003 tejbeer 1592
 
32839 amit.gupta 1593
    @Autowired
1594
    private BrandLimitRepository brandLimitRepository;
30044 tejbeer 1595
 
31663 amit.gupta 1596
 
32839 amit.gupta 1597
    private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING,
1598
            OrderStatus.ACCEPTED);
30003 tejbeer 1599
 
32839 amit.gupta 1600
    public static final Map<String, Double> Brand_Amount_Limit = new HashMap<>();
30003 tejbeer 1601
 
32839 amit.gupta 1602
    static {
30044 tejbeer 1603
 
32839 amit.gupta 1604
        Brand_Amount_Limit.put("accessories", 10000.00);
1605
        Brand_Amount_Limit.put("TV", 27000.00);
1606
    }
30003 tejbeer 1607
 
33806 tejus.loha 1608
 
32839 amit.gupta 1609
    @RequestMapping(value = "/getPartnersBrandWiseDetail", method = RequestMethod.GET)
1610
    public String getPartnersBrandWiseDetail(HttpServletRequest request, Model model) throws Exception {
30003 tejbeer 1611
 
32839 amit.gupta 1612
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1613
        String email = loginDetails.getEmailId();
30003 tejbeer 1614
 
34035 ranu 1615
        List<String> brands = ProfitMandiConstants.BRANDS;
30003 tejbeer 1616
 
32839 amit.gupta 1617
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1618
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
30003 tejbeer 1619
 
37977 aman 1620
        // Disha widget for RBMs only; a failed lookup hides Disha instead of breaking the page
1621
        boolean isRBM = false;
1622
        try {
1623
            isRBM = authUser != null && positionRepository.selectPositionByAuthId(authUser.getId()).stream()
1624
                    .anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
1625
        } catch (Exception e) {
1626
            LOGGER.warn("Disha: could not check RBM position for {}", email, e);
1627
        }
1628
        String dishaKey = dishaRbmKey == null ? "" : dishaRbmKey.trim();
1629
        // Ira's way for now (Tanay, 2026-10-30): Disha is on this page for any logged-in staff member,
1630
        // named by the login email; Disha's own server lets in only a @smartdukaan.com login with
1631
        // partners assigned to it (the position check above was false for an RBM login, so it is
1632
        // logged, not used). With the key set (-Ddisha.rbm.key) the page also carries signed
1633
        // per-store passes, which Disha prefers.
1634
        if (!isRBM) LOGGER.info("Disha: {} has no RBM position; Disha's server decides by partners", email);
1635
        boolean dishaOn = authUser != null;
1636
        model.addAttribute("authEmail", email);
1637
        model.addAttribute("dishaOn", dishaOn);
1638
        model.addAttribute("dishaServer", dishaServer.trim().replaceAll("/+$", ""));
1639
 
32839 amit.gupta 1640
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
30003 tejbeer 1641
 
32839 amit.gupta 1642
        Map<Integer, Map<String, Double>> fofoIdBrandAmountMap = new HashMap<>();
35484 ranu 1643
        Map<Integer, Map<String, Double>> fofoIdBrandQtyMap = new HashMap<>();
30003 tejbeer 1644
 
32839 amit.gupta 1645
        Map<Integer, InStockAccessoriesTvFofoIdModel> inStockAccessTv = new HashMap<>();
1646
        Map<Integer, InStockAccessoriesTvFofoIdModel> pendingIndentAccessTv = new HashMap<>();
1647
        Map<Integer, InStockAccessoriesTvFofoIdModel> grnPendingAccessTvOrders = new HashMap<>();
35490 ranu 1648
 
1649
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> inStockQtyAccessTv = new HashMap<>();
1650
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> pendingIndentQtyAccessTv = new HashMap<>();
1651
        Map<Integer, InStockAccessoriesTvQtyFofoIdModel> grnPendingQtyAccessTvOrders = new HashMap<>();
32839 amit.gupta 1652
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1653
        Map<Integer, CustomRetailer> customRetailers = new HashMap<>();
1654
        Map<Integer, PartnerType> fofoIdPartnerTypeMap = new HashMap<>();
30003 tejbeer 1655
 
32839 amit.gupta 1656
        if (fofoIds != null && fofoIds.size() > 0) {
1657
            List<Integer> fofoIdList = new ArrayList<>(fofoIds);
30003 tejbeer 1658
 
32839 amit.gupta 1659
            Map<Integer, ActivationType> partnerActivationType = fofoStoreRepository.selectByRetailerIds(fofoIdList)
1660
                    .stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getActivationType()));
1661
            //Only L3 and above can change the accessType
35395 amit 1662
            boolean canChangeActionType = positionRepository.selectAllByAuthUserId(authUser.getId())
32839 amit.gupta 1663
                    .stream().filter(x -> x.getEscalationType().isGreaterThanEqualTo(EscalationType.L3)).count() > 0;
1664
            model.addAttribute("canChangeActivationType", canChangeActionType);
1665
            model.addAttribute("partnerActivationType", partnerActivationType);
1666
            model.addAttribute("activationTypes", ActivationType.values());
30046 tejbeer 1667
 
32839 amit.gupta 1668
            Map<Integer, FofoReportingModel> partnerSalesHeadersMap = csService.getPartnerIdSalesHeaders();
30046 tejbeer 1669
 
32839 amit.gupta 1670
            model.addAttribute("partnerSalesHeadersMap", partnerSalesHeadersMap);
30003 tejbeer 1671
 
32839 amit.gupta 1672
            Map<Integer, Map<String, Float>> partnerBrandLimitMap = brandLimitRepository.selectAllPartnerBrandLimit()
1673
                    .stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1674
                            Collectors.toMap(x -> x.getBrand(), x -> x.getBrandLimit())));
30044 tejbeer 1675
 
32839 amit.gupta 1676
            model.addAttribute("partnerBrandLimitMap", partnerBrandLimitMap);
1677
            customRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1678
                    .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1679
            Map<Integer, Map<String, Double>> inStockBrandModel;
35484 ranu 1680
            Map<Integer, Map<String, Double>> inStockBrandModelQty;
32839 amit.gupta 1681
            Map<Integer, Map<String, Double>> pendingIndent;
35484 ranu 1682
            Map<Integer, Map<String, Double>> pendingIndentQty;
32839 amit.gupta 1683
            Map<Integer, Map<String, Double>> grnPendingOrders;
35484 ranu 1684
            Map<Integer, Map<String, Double>> grnPendingOrdersQty;
30044 tejbeer 1685
 
32839 amit.gupta 1686
            // mobile
35490 ranu 1687
            List<InStockBrandFofoIdModel> inStockBrandFofoIdModels = currentInventorySnapshotRepository.selectSumInStockMobiletabletGroupByBrand(fofoIdList);
1688
 
1689
            inStockBrandModel = inStockBrandFofoIdModels
32839 amit.gupta 1690
                    .stream()
1691
                    .collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1692
                            Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1693
                                    Collectors.summingDouble(InStockBrandFofoIdModel::getAmount))));
30003 tejbeer 1694
 
35490 ranu 1695
            inStockBrandModelQty = inStockBrandFofoIdModels
35484 ranu 1696
                    .stream()
1697
                    .collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1698
                            Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1699
                                    Collectors.summingDouble(InStockBrandFofoIdModel::getQty))));
1700
 
35490 ranu 1701
            List<Order> pendingIndentOrders = transactionService.getInTransitOrders(fofoIdList);
1702
 
1703
            pendingIndent = pendingIndentOrders.stream()
32839 amit.gupta 1704
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1705
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1706
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1707
                                    Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
30003 tejbeer 1708
 
35490 ranu 1709
 
1710
            pendingIndentQty = pendingIndentOrders.stream()
35484 ranu 1711
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1712
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1713
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1714
                                    Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));
1715
 
35490 ranu 1716
 
1717
            List<Order> grnPendingOrderList = orderRepository.selectPendingGrnOrders(fofoIdList);
1718
 
1719
            grnPendingOrders = grnPendingOrderList.stream()
32839 amit.gupta 1720
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1721
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1722
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1723
                                    Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
35490 ranu 1724
            grnPendingOrdersQty = grnPendingOrderList.stream()
35484 ranu 1725
                    .filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
1726
                    .collect(Collectors.groupingBy(x -> x.getRetailerId(),
1727
                            Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1728
                                    Collectors.summingDouble(y -> (double) y.getLineItem().getQuantity()))));
30003 tejbeer 1729
 
32839 amit.gupta 1730
            // accessories
1731
            inStockAccessTv = currentInventorySnapshotRepository.selectSumInStockAccessoriesAndTv(fofoIdList).stream()
1732
                    .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1733
 
32839 amit.gupta 1734
            pendingIndentAccessTv = orderRepository.selectAllPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1735
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1736
 
32839 amit.gupta 1737
            grnPendingAccessTvOrders = orderRepository.selectAllGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1738
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
30003 tejbeer 1739
 
35490 ranu 1740
 
1741
            inStockQtyAccessTv = currentInventorySnapshotRepository.selectQtySumInStockAccessoriesAndTv(fofoIdList).stream()
1742
                    .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1743
 
1744
            pendingIndentQtyAccessTv = orderRepository.selectAllQtyPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1745
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1746
 
1747
            grnPendingQtyAccessTvOrders = orderRepository.selectAllQtyGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1748
                    .stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1749
 
35462 amit 1750
            // Bulk fetch partner types to avoid N+1 queries
1751
            fofoIdPartnerTypeMap = partnerTypeChangeService.getTypesForFofoIds(new ArrayList<>(customRetailers.keySet()), LocalDate.now());
1752
 
32839 amit.gupta 1753
            for (Entry<Integer, CustomRetailer> customRetailer : customRetailers.entrySet()) {
1754
                Map<String, Double> stockBrand = inStockBrandModel.get(customRetailer.getKey());
35484 ranu 1755
                Map<String, Double> stockBrandQty = inStockBrandModelQty.get(customRetailer.getKey());
32839 amit.gupta 1756
                Map<String, Double> pendingIndentBrand = pendingIndent.get(customRetailer.getKey());
35484 ranu 1757
                Map<String, Double> pendingIndentBrandQty = pendingIndentQty.get(customRetailer.getKey());
32839 amit.gupta 1758
                Map<String, Double> grnBrand = grnPendingOrders.get(customRetailer.getKey());
35484 ranu 1759
                Map<String, Double> grnBrandQty = grnPendingOrdersQty.get(customRetailer.getKey());
32839 amit.gupta 1760
                double totalAmount = 0;
35484 ranu 1761
                double totalQty = 0;
30024 tejbeer 1762
 
32839 amit.gupta 1763
                Map<String, Double> brandAmountMap = new HashMap<>();
35484 ranu 1764
                Map<String, Double> brandQtyMap = new HashMap<>();
32839 amit.gupta 1765
                for (String brand : brands) {
30024 tejbeer 1766
 
32839 amit.gupta 1767
                    double stockValue = 0;
35484 ranu 1768
                    double stockQty = 0;
32839 amit.gupta 1769
                    double pendingValue = 0;
35484 ranu 1770
                    double pendingQty = 0;
32839 amit.gupta 1771
                    double grnValue = 0;
35484 ranu 1772
                    double grnQty = 0;
32839 amit.gupta 1773
                    if (stockBrand != null) {
30024 tejbeer 1774
 
32839 amit.gupta 1775
                        if (stockBrand.get(brand) != null) {
1776
                            stockValue = stockBrand.get(brand);
1777
                        }
1778
                    }
30024 tejbeer 1779
 
35484 ranu 1780
                    if (stockBrandQty != null) {
1781
 
1782
                        if (stockBrandQty.get(brand) != null) {
1783
                            stockQty = stockBrandQty.get(brand);
1784
                        }
1785
                    }
1786
 
32839 amit.gupta 1787
                    if (pendingIndentBrand != null) {
1788
                        if (pendingIndentBrand.get(brand) != null) {
1789
                            pendingValue = pendingIndentBrand.get(brand);
1790
                        }
1791
                    }
35484 ranu 1792
                    if (pendingIndentBrandQty != null) {
1793
                        if (pendingIndentBrandQty.get(brand) != null) {
1794
                            pendingQty = pendingIndentBrandQty.get(brand);
1795
                        }
1796
                    }
30024 tejbeer 1797
 
32839 amit.gupta 1798
                    if (grnBrand != null) {
1799
                        if (grnBrand.get(brand) != null) {
1800
                            grnValue = grnBrand.get(brand);
1801
                        }
1802
                    }
30024 tejbeer 1803
 
35484 ranu 1804
                    if (grnBrandQty != null) {
1805
                        if (grnBrandQty.get(brand) != null) {
1806
                            grnQty = grnBrandQty.get(brand);
1807
                        }
1808
                    }
1809
 
32839 amit.gupta 1810
                    totalAmount = stockValue + pendingValue + grnValue;
30024 tejbeer 1811
 
35484 ranu 1812
                    totalQty = stockQty + pendingQty + grnQty;
1813
 
32839 amit.gupta 1814
                    brandAmountMap.put(brand, totalAmount);
30024 tejbeer 1815
 
35484 ranu 1816
                    brandQtyMap.put(brand, totalQty);
1817
 
32839 amit.gupta 1818
                }
30024 tejbeer 1819
 
32839 amit.gupta 1820
                fofoIdBrandAmountMap.put(customRetailer.getKey(), brandAmountMap);
35484 ranu 1821
                fofoIdBrandQtyMap.put(customRetailer.getKey(), brandQtyMap);
30024 tejbeer 1822
 
32839 amit.gupta 1823
            }
30024 tejbeer 1824
 
32839 amit.gupta 1825
            List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
1826
                    .selectAll(new ArrayList<>(fofoIdList), LocalDate.now().minusDays(1));
1827
            if (!partnerDailyInvestments.isEmpty()) {
1828
                partnerDailyInvestmentMap = partnerDailyInvestments.stream()
1829
                        .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1830
            }
30024 tejbeer 1831
 
32839 amit.gupta 1832
        }
33806 tejus.loha 1833
        Map<Integer, MonthlyTarget> fofoIdMonthlyTargetMap = monthlyTargetRepository.selectByDateAndFofoIds(YearMonth.now(), new ArrayList<>(fofoIds)).stream()
1834
                .collect(Collectors.toMap(MonthlyTarget::getFofoId, x -> x,
1835
                        (existing, replacement) -> replacement  // Keep the last entry
1836
                ));
1837
 
1838
        Map<Integer, Float> fofoMTDSaleMap = fofoOrderRepository.selectSaleSumGroupByFofoIds(YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now());
1839
 
1840
        Map<Integer, Double> currentMonthTillDateRetailerPOValueMap = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(new ArrayList<>(fofoIds),
1841
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
1842
                YearMonth.now().atDay(1).atStartOfDay(), LocalDateTime.now()).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
1843
 
35811 amit 1844
        Map<Integer, BulkCreditSummary> bulkSummaryMap = sdCreditService.getCreditSummaryBulk();
33812 tejus.loha 1845
        Map<Integer, BigDecimal> totalDueMap = new HashMap<>();
35811 amit 1846
        for (int fofoId : fofoIds) {
1847
            BulkCreditSummary summary = bulkSummaryMap.get(fofoId);
1848
            if (summary != null) {
1849
                totalDueMap.put(fofoId, summary.getTotalDue());
33812 tejus.loha 1850
            }
1851
        }
1852
 
33813 tejus.loha 1853
 
32839 amit.gupta 1854
        //Only L3 and above can change the activationType
30024 tejbeer 1855
 
37977 aman 1856
        // Disha passes: one per store on the page plus a list-only one, all expiring together
1857
        String dishaListToken = "";
1858
        Map<String, String> dishaTokens = new HashMap<>();
1859
        if (dishaOn && !dishaKey.isEmpty()) {
1860
            long dishaExpiresAt = System.currentTimeMillis() / 1000L + DISHA_TOKEN_TTL_S;
1861
            dishaListToken = DishaRbmToken.mint(dishaKey, "", email, dishaExpiresAt);
1862
            for (CustomRetailer cr : customRetailers.values()) {
1863
                if (cr == null || cr.getCode() == null || cr.getCode().trim().isEmpty()) {
1864
                    continue;
1865
                }
1866
                dishaTokens.put(cr.getCode(), DishaRbmToken.mint(dishaKey, cr.getCode(), email, dishaExpiresAt));
1867
            }
1868
        }
1869
        model.addAttribute("dishaListToken", dishaListToken);
1870
        model.addAttribute("dishaTokensJson", new JSONObject(dishaTokens).toString());
1871
 
32839 amit.gupta 1872
        model.addAttribute("customRetailers", customRetailers);
33812 tejus.loha 1873
        model.addAttribute("totalDueMap", totalDueMap);
33806 tejus.loha 1874
        model.addAttribute("fofoMTDSaleMap", fofoMTDSaleMap);
1875
        model.addAttribute("fofoIdMonthlyTargetMap", fofoIdMonthlyTargetMap);
1876
        model.addAttribute("currentMonthTillDateRetailerPOValueMap", currentMonthTillDateRetailerPOValueMap);
30003 tejbeer 1877
 
34759 amit.gupta 1878
        //LOGGER.info("fofoIdBrandAmountMap" + fofoIdBrandAmountMap);
30003 tejbeer 1879
 
32839 amit.gupta 1880
        model.addAttribute("partnerDailyInvestmentMap", partnerDailyInvestmentMap);
30003 tejbeer 1881
 
32839 amit.gupta 1882
        model.addAttribute("brands", brands);
30003 tejbeer 1883
 
32839 amit.gupta 1884
        model.addAttribute("brandAmountLimit", Brand_Amount_Limit);
1885
        model.addAttribute("fofoIdBrandAmountMap", fofoIdBrandAmountMap);
35484 ranu 1886
        model.addAttribute("fofoIdBrandQtyMap", fofoIdBrandQtyMap);
30003 tejbeer 1887
 
32839 amit.gupta 1888
        model.addAttribute("inStockAccessTv", inStockAccessTv);
1889
        model.addAttribute("pendingIndentAccessTv", pendingIndentAccessTv);
1890
        model.addAttribute("grnPendingAccessTvOrders", grnPendingAccessTvOrders);
35490 ranu 1891
        model.addAttribute("inStockQtyAccessTv", inStockQtyAccessTv);
1892
        model.addAttribute("pendingIndentQtyAccessTv", pendingIndentQtyAccessTv);
1893
        model.addAttribute("grnPendingQtyAccessTvOrders", grnPendingQtyAccessTvOrders);
32839 amit.gupta 1894
        model.addAttribute("fofoIdPartnerTypeMap", fofoIdPartnerTypeMap);
30003 tejbeer 1895
 
1896
 
32839 amit.gupta 1897
        return "partner-brandwise-detail";
1898
    }
30046 tejbeer 1899
 
32839 amit.gupta 1900
    @RequestMapping(value = "/changeActivationType", method = RequestMethod.POST)
1901
    public String changeActivationType(HttpServletRequest request, @RequestParam String code,
1902
                                       @RequestParam ActivationType activationType, Model model) throws Exception {
30046 tejbeer 1903
 
32839 amit.gupta 1904
        FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(code);
30046 tejbeer 1905
 
32839 amit.gupta 1906
        fofoStore.setActivationType(activationType);
30046 tejbeer 1907
 
32839 amit.gupta 1908
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1909
        return "response";
30046 tejbeer 1910
 
32839 amit.gupta 1911
    }
30017 amit.gupta 1912
 
32839 amit.gupta 1913
    @RequestMapping(value = "/createPo", method = RequestMethod.POST)
1914
    public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1915
            throws Exception {
1916
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1917
        SuggestedPo mp = new SuggestedPo();
1918
        mp.setFofoId(monthlyPoModel.getFofoId());
1919
        mp.setCreateTimestamp(LocalDateTime.now());
1920
        mp.setStatus("open");
1921
        mp.setAuthId(loginDetails.getEmailId());
1922
        suggestedPoRepository.persist(mp);
30017 amit.gupta 1923
 
32839 amit.gupta 1924
        for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1925
            SuggestedPoDetail mpd = new SuggestedPoDetail();
1926
            mpd.setItemId(poId.getItemId());
1927
            mpd.setQuantity(poId.getQty());
1928
            mpd.setUpdatedTimestamp(LocalDateTime.now());
1929
            mpd.setPoId(mp.getId());
1930
            suggestedPoDetailRepository.persist(mpd);
1931
        }
30017 amit.gupta 1932
 
32839 amit.gupta 1933
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
1934
        sendNotificationModel.setCampaignName("Alert");
1935
        sendNotificationModel.setMessage("Suggested Po");
1936
        sendNotificationModel.setType("url");
1937
        sendNotificationModel.setTitle("Alert");
1938
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
1939
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1940
        sendNotificationModel.setMessageType(MessageType.notification);
1941
        int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
30017 amit.gupta 1942
 
32839 amit.gupta 1943
        sendNotificationModel.setUserIds(Arrays.asList(userId));
1944
        notificationService.sendNotification(sendNotificationModel);
1945
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
30017 amit.gupta 1946
 
32839 amit.gupta 1947
        return "response";
1948
    }
30003 tejbeer 1949
 
34087 ranu 1950
 
34437 ranu 1951
    @RequestMapping(value = "/createSuggestedPo", method = RequestMethod.POST)
1952
    public String createSuggestedPo(HttpServletRequest request, @RequestBody List<SuggestedPoCatalogModel> poCatalogModel, @RequestParam int fofoId, Model model)
1953
            throws Exception {
1954
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1955
        List<SuggestedPo> suggestedPos = suggestedPoRepository.selectAllOpenPoByFofoId(fofoId);
1956
        for (SuggestedPo suggestedPo : suggestedPos) {
1957
            suggestedPo.setStatus("closed");
1958
        }
1959
        SuggestedPo mp = new SuggestedPo();
1960
        mp.setFofoId(fofoId);
1961
        mp.setCreateTimestamp(LocalDateTime.now());
1962
        mp.setStatus("open");
1963
        mp.setAuthId(loginDetails.getEmailId());
1964
        suggestedPoRepository.persist(mp);
1965
 
1966
        for (SuggestedPoCatalogModel catalogModel : poCatalogModel) {
1967
            SuggestedPoDetail mpd = new SuggestedPoDetail();
34449 ranu 1968
            mpd.setItemId(catalogModel.getItemId());
34437 ranu 1969
            mpd.setQuantity(catalogModel.getQty());
1970
            mpd.setUpdatedTimestamp(LocalDateTime.now());
1971
            mpd.setPoId(mp.getId());
1972
            suggestedPoDetailRepository.persist(mpd);
1973
        }
1974
 
1975
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
1976
        sendNotificationModel.setCampaignName("Alert");
1977
        sendNotificationModel.setMessage("Suggested Po");
1978
        sendNotificationModel.setType("url");
1979
        sendNotificationModel.setTitle("Alert");
1980
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
1981
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1982
        sendNotificationModel.setMessageType(MessageType.notification);
1983
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
1984
 
1985
        sendNotificationModel.setUserIds(Arrays.asList(userId));
1986
        notificationService.sendNotification(sendNotificationModel);
1987
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1988
 
1989
        return "response";
1990
    }
1991
 
1992
 
34087 ranu 1993
    @RequestMapping(value = "/getPartnerShortageStockDetail", method = RequestMethod.GET)
1994
    public String getPartnerShortageStockDetail(HttpServletRequest request,
34098 ranu 1995
                                                @RequestParam(required = false, defaultValue = "") String brand, @RequestParam int fofoId, Model model)
32839 amit.gupta 1996
            throws Exception {
30003 tejbeer 1997
 
32839 amit.gupta 1998
        Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService
1999
                .getSaholicPOItems();
30003 tejbeer 2000
 
32839 amit.gupta 2001
        List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
2002
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2003
        Map<Integer, Integer> processingOrderMap = null;
2004
        Map<Integer, Integer> catalogIdAndQtyMap = null;
2005
        Map<Integer, Integer> grnPendingOrdersMap = null;
30044 tejbeer 2006
 
34490 ranu 2007
        Map<String, Set<PartnerStockDetailModel>> brandToUniqueItemsMap = new HashMap<>();
34449 ranu 2008
 
34490 ranu 2009
        List<PartnerStockDetailModel> inStocks = new ArrayList<>();
2010
        Map<String, PartnerStockDetailModel> inStocksDescriptionModelMap = new HashMap<>();
30044 tejbeer 2011
 
34490 ranu 2012
        List<PartnerStockDetailModel> grnPendings = new ArrayList<>();
2013
        Map<String, PartnerStockDetailModel> grnPendingsDescriptionModelMap = new HashMap<>();
30044 tejbeer 2014
 
34449 ranu 2015
 
34490 ranu 2016
        List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();
2017
        Map<String, PartnerStockDetailModel> pendingIndentsDescriptionModelMap = new HashMap<>();
30003 tejbeer 2018
 
32839 amit.gupta 2019
        Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
2020
                .stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
30003 tejbeer 2021
 
34425 ranu 2022
 
32839 amit.gupta 2023
        if (!currentInventorySnapshot.isEmpty()) {
34425 ranu 2024
            catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
2025
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2026
                            Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
34490 ranu 2027
            inStocks.addAll(getBrandItemwiseDetail(brand, catalogIdAndQtyMap));
34449 ranu 2028
            inStocksDescriptionModelMap = inStocks.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
32839 amit.gupta 2029
        }
34449 ranu 2030
 
32839 amit.gupta 2031
        Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
2032
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2033
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2034
        if (!grnPendingOrders.isEmpty()) {
34425 ranu 2035
            grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
2036
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2037
                            Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
34490 ranu 2038
            grnPendings.addAll(getBrandItemwiseDetail(brand, grnPendingOrdersMap));
34449 ranu 2039
            grnPendingsDescriptionModelMap = grnPendings.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
30003 tejbeer 2040
 
32839 amit.gupta 2041
        }
30003 tejbeer 2042
 
32839 amit.gupta 2043
        Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
2044
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2045
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2046
        if (!processingOrder.isEmpty()) {
34425 ranu 2047
            processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
2048
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2049
                            Collectors.summingInt(x -> processingOrder.get(x.getId()))));
34490 ranu 2050
            pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));
34449 ranu 2051
            pendingIndentsDescriptionModelMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getItemDescription(), x -> x));
30003 tejbeer 2052
 
32839 amit.gupta 2053
        }
30003 tejbeer 2054
 
32839 amit.gupta 2055
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
2056
                .collect(Collectors.toList());
2057
        LOGGER.info("regionIds" + regionIds);
2058
        if (regionIds.size() == 0) {
2059
            LOGGER.info("No region found for partner {}", fofoId);
30003 tejbeer 2060
 
32839 amit.gupta 2061
        }
34456 ranu 2062
 
2063
//        this code is using for focusedModel()
32839 amit.gupta 2064
        Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository
2065
                .selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,
2066
                        Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
30003 tejbeer 2067
 
32839 amit.gupta 2068
        for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
2069
            List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());
30003 tejbeer 2070
 
32839 amit.gupta 2071
            if (brand.equals("undefined") || items.get(0).getBrand().equals(brand)) {
30003 tejbeer 2072
 
32839 amit.gupta 2073
                FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(), entry.getKey(),
2074
                        processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2075
                        warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2076
 
32839 amit.gupta 2077
                focusedModelShortageList.add(fm);
2078
            } else if (brand.equals("accessories")) {
30003 tejbeer 2079
 
32839 amit.gupta 2080
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2081
                    if (items.get(0).getCategoryId() != 0) {
2082
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30003 tejbeer 2083
 
32839 amit.gupta 2084
                        if (category.getParentCategoryId() == 10011) {
2085
                            FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2086
                                    entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2087
                                    warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2088
 
32839 amit.gupta 2089
                            focusedModelShortageList.add(fm);
30003 tejbeer 2090
 
32839 amit.gupta 2091
                        }
2092
                    }
30003 tejbeer 2093
 
32839 amit.gupta 2094
                }
30003 tejbeer 2095
 
32839 amit.gupta 2096
            } else if (brand.equals("TV")) {
30003 tejbeer 2097
 
32839 amit.gupta 2098
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2099
                    LOGGER.info("items.get(0).getCategoryId()" + items.get(0).getCategoryId());
2100
                    if (items.get(0).getCategoryId() != 0) {
30003 tejbeer 2101
 
32839 amit.gupta 2102
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30003 tejbeer 2103
 
32839 amit.gupta 2104
                        if (category.getParentCategoryId() == 14200) {
2105
                            FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2106
                                    entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
2107
                                    warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 2108
 
32839 amit.gupta 2109
                            focusedModelShortageList.add(fm);
30003 tejbeer 2110
 
32839 amit.gupta 2111
                        }
2112
                    }
30003 tejbeer 2113
 
32839 amit.gupta 2114
                }
30003 tejbeer 2115
 
32839 amit.gupta 2116
            }
30003 tejbeer 2117
 
32839 amit.gupta 2118
        }
30003 tejbeer 2119
 
34490 ranu 2120
        List<PartnerStockDetailModel> allStockItems = new ArrayList<>();
34449 ranu 2121
        allStockItems.addAll(inStocks);
2122
        allStockItems.addAll(grnPendings);
2123
        allStockItems.addAll(pendingIndents);
34760 amit.gupta 2124
        //LOGGER.info("allStockItems {}", allStockItems);
34449 ranu 2125
        brandToUniqueItemsMap =
2126
                allStockItems.stream().collect(
2127
                        Collectors.groupingBy(
34490 ranu 2128
                                PartnerStockDetailModel::getBrand,
34449 ranu 2129
                                Collectors.toSet()
2130
                        )
2131
                );
30003 tejbeer 2132
 
34449 ranu 2133
 
32839 amit.gupta 2134
        model.addAttribute("focusedModelShortageList", focusedModelShortageList);
30044 tejbeer 2135
 
32839 amit.gupta 2136
        model.addAttribute("inStocks", inStocks);
34449 ranu 2137
        model.addAttribute("inStocksDescriptionModelMap", inStocksDescriptionModelMap);
30044 tejbeer 2138
 
34449 ranu 2139
        model.addAttribute("brandToUniqueItemsMap", brandToUniqueItemsMap);
34490 ranu 2140
        model.addAttribute("fofoId", fofoId);
34425 ranu 2141
 
32839 amit.gupta 2142
        model.addAttribute("grnPendings", grnPendings);
34449 ranu 2143
        model.addAttribute("grnPendingsDescriptionModelMap", grnPendingsDescriptionModelMap);
30044 tejbeer 2144
 
32839 amit.gupta 2145
        model.addAttribute("pendingIndents", pendingIndents);
34449 ranu 2146
        model.addAttribute("pendingIndentsDescriptionModelMap", pendingIndentsDescriptionModelMap);
30044 tejbeer 2147
 
32839 amit.gupta 2148
        model.addAttribute("customRetailer", customRetailer);
30044 tejbeer 2149
 
32839 amit.gupta 2150
        model.addAttribute("brand", brand);
30044 tejbeer 2151
 
32839 amit.gupta 2152
        if (brand.equals("undefined")) {
30044 tejbeer 2153
 
32839 amit.gupta 2154
            Map<String, List<FocusedModelShortageModel>> focusedModelShortageBrandMap = focusedModelShortageList
2155
                    .stream().collect(Collectors.groupingBy(x -> x.getBrandName()));
30044 tejbeer 2156
 
34490 ranu 2157
            Map<String, List<PartnerStockDetailModel>> inStockBrandMap = inStocks.stream()
32839 amit.gupta 2158
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2159
 
32839 amit.gupta 2160
            LOGGER.info("inStockBrandMap" + inStockBrandMap);
30044 tejbeer 2161
 
34490 ranu 2162
            Map<String, List<PartnerStockDetailModel>> grnPendingBrandMap = grnPendings.stream()
32839 amit.gupta 2163
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2164
 
32839 amit.gupta 2165
            LOGGER.info("grnPendingBrandMap" + grnPendingBrandMap);
30044 tejbeer 2166
 
34490 ranu 2167
            Map<String, List<PartnerStockDetailModel>> pendingIndentBrandMap = pendingIndents.stream()
32839 amit.gupta 2168
                    .collect(Collectors.groupingBy(x -> x.getBrand()));
30044 tejbeer 2169
 
32839 amit.gupta 2170
            LOGGER.info("pendingIndentBrandMap" + pendingIndentBrandMap);
30044 tejbeer 2171
 
32839 amit.gupta 2172
            model.addAttribute("inStockBrandMap", inStockBrandMap);
30044 tejbeer 2173
 
32839 amit.gupta 2174
            model.addAttribute("grnPendingBrandMap", grnPendingBrandMap);
30044 tejbeer 2175
 
32839 amit.gupta 2176
            model.addAttribute("focusedModelShortageBrandMap", focusedModelShortageBrandMap);
30044 tejbeer 2177
 
32839 amit.gupta 2178
            model.addAttribute("pendingIndentBrandMap", pendingIndentBrandMap);
30003 tejbeer 2179
 
32839 amit.gupta 2180
        }
34035 ranu 2181
 
34087 ranu 2182
        return "partner-stock-detail";
2183
 
2184
    }
2185
 
34397 ranu 2186
 
34449 ranu 2187
    @RequestMapping(value = "/getPoCatalogsItems", method = RequestMethod.GET)
34581 ranu 2188
    public String getPoCatalogsItems(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, @RequestParam float price, Model model)
34449 ranu 2189
            throws Exception {
2190
        List<Item> poItems = itemRepository.selectAllByCatalogItemId(catalogId);
34581 ranu 2191
 
2192
        List<Integer> itemIds = poItems.stream().map(x -> x.getId()).collect(Collectors.toList());
2193
 
2194
        Map<Integer, Integer> saholicInventoryMap = saholicInventoryService.getTotalAvailabilityByItemIds(itemIds);
2195
 
2196
        Set<Integer> availableStockItemIds = saholicInventoryMap.entrySet().stream()
2197
                .filter(x -> x.getValue() > 0)
2198
                .map(Map.Entry::getKey)
2199
                .collect(Collectors.toSet());
2200
 
2201
        List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == warehouseId)).collect(Collectors.toList());
2202
 
2203
        Set<Integer> intransitItemIds = warehouseIntransitDataModels.stream()
2204
                .filter(x -> x.getQty() > 0)
2205
                .map(WarehouseIntransitDataModel::getItemId)
2206
                .collect(Collectors.toSet());
2207
 
2208
        // Filter intransitItemIds to only those in itemIds
2209
        Set<Integer> intransitItemIdsFiltered = new HashSet<>(intransitItemIds);
2210
        intransitItemIdsFiltered.retainAll(itemIds);
2211
 
2212
        Set<Integer> itemIdsWithBothStocks = new HashSet<>();
2213
        itemIdsWithBothStocks.addAll(intransitItemIdsFiltered); // keeps only the common ones
2214
        itemIdsWithBothStocks.addAll(availableStockItemIds); // keeps only the common ones
2215
 
2216
        LOGGER.info("itemIds {}", itemIds);
2217
        LOGGER.info("itemIdsWithBothStocks {}", itemIdsWithBothStocks);
2218
        LOGGER.info("availableStockItemIds {}", availableStockItemIds);
2219
        LOGGER.info("intransitItemIdsFiltered {}", intransitItemIdsFiltered);
35782 ranu 2220
        List<Item> instockItems = new ArrayList<>();
2221
        if (itemIdsWithBothStocks.isEmpty() && availableStockItemIds.isEmpty() && intransitItemIdsFiltered.isEmpty()) {
2222
            instockItems = itemRepository.selectByIds(itemIds);
2223
        } else {
2224
            instockItems = itemRepository.selectByIds(itemIdsWithBothStocks);
2225
        }
34581 ranu 2226
 
35782 ranu 2227
 
34581 ranu 2228
        model.addAttribute("poItems", instockItems);
34449 ranu 2229
        model.addAttribute("price", price);
2230
 
2231
        return "po-catalog-items";
2232
    }
2233
 
2234
 
34490 ranu 2235
    @RequestMapping(value = "/getItemsByCatalog", method = RequestMethod.GET)
2236
    public ResponseEntity<?> getItemsByCatalog(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int fofoId, Model model)
2237
            throws Exception {
2238
        List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
34495 ranu 2239
        Map<Integer, Item> itemMap = items.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
34490 ranu 2240
        Set<Integer> itemSet = items.stream().map(x -> x.getId()).collect(Collectors.toSet());
2241
        List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemSet);
35771 ranu 2242
 
2243
        // Get activated but not sold inventory items for this fofoId
2244
        List<InventoryItem> activatedNotSoldItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
2245
 
2246
        // Group activated items by itemId with their serial numbers
2247
        Map<Integer, List<String>> activatedItemImeiMap = activatedNotSoldItems.stream()
2248
                .collect(Collectors.groupingBy(
2249
                        InventoryItem::getItemId,
2250
                        Collectors.mapping(InventoryItem::getSerialNumber, Collectors.toList())
2251
                ));
2252
 
34495 ranu 2253
        List<InStockItemDetailModel> inStockItemDetailModels = new ArrayList<>();
35776 ranu 2254
 
2255
        // Add in-stock items
34495 ranu 2256
        for (CurrentInventorySnapshot snap : currentInventorySnapshots) {
2257
            InStockItemDetailModel inStockItemDetailModel = new InStockItemDetailModel();
2258
            inStockItemDetailModel.setAvailability(snap.getAvailability());
2259
            inStockItemDetailModel.setItemId(snap.getItemId());
2260
            inStockItemDetailModel.setCatalogId(itemMap.get(snap.getItemId()).getCatalogItemId());
2261
            inStockItemDetailModel.setItemDescription(itemMap.get(snap.getItemId()).getItemDescription());
2262
            inStockItemDetailModel.setFofoId(snap.getFofoId());
35776 ranu 2263
            inStockItemDetailModel.setStockType("IN_STOCK");
35771 ranu 2264
            // Check if this item has any activated but not sold IMEIs and set the IMEI list
2265
            List<String> activatedImeis = activatedItemImeiMap.get(snap.getItemId());
2266
            if (activatedImeis != null && !activatedImeis.isEmpty()) {
2267
                inStockItemDetailModel.setHasActivatedImei(true);
2268
                inStockItemDetailModel.setActivatedImeis(activatedImeis);
2269
            }
34495 ranu 2270
            inStockItemDetailModels.add(inStockItemDetailModel);
2271
        }
2272
 
35776 ranu 2273
        // Get GRN pending orders for this fofoId and filter by catalog items
2274
        Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
2275
                .filter(x -> itemSet.contains(x.getLineItem().getItemId()))
2276
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2277
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2278
 
2279
        // Add GRN pending items
2280
        for (Map.Entry<Integer, Integer> entry : grnPendingOrders.entrySet()) {
2281
            int itemId = entry.getKey();
2282
            int qty = entry.getValue();
2283
            if (itemMap.containsKey(itemId)) {
2284
                InStockItemDetailModel grnModel = new InStockItemDetailModel();
2285
                grnModel.setAvailability(qty);
2286
                grnModel.setItemId(itemId);
2287
                grnModel.setCatalogId(itemMap.get(itemId).getCatalogItemId());
2288
                grnModel.setItemDescription(itemMap.get(itemId).getItemDescription());
2289
                grnModel.setFofoId(fofoId);
2290
                grnModel.setStockType("GRN_PENDING");
2291
                inStockItemDetailModels.add(grnModel);
2292
            }
2293
        }
2294
 
34495 ranu 2295
        return responseSender.ok(inStockItemDetailModels);
34490 ranu 2296
    }
34449 ranu 2297
 
35765 ranu 2298
    @RequestMapping(value = "/indent/getOurStockDetails", method = RequestMethod.GET)
2299
    public ResponseEntity<?> getOurStockDetails(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, Model model)
2300
            throws Exception {
2301
        try {
2302
            // Get all items by catalogId
2303
            List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
2304
            List<Integer> itemIds = items.stream().map(Item::getId).collect(Collectors.toList());
2305
 
2306
            if (itemIds.isEmpty()) {
2307
                return responseSender.ok(Collections.emptyList());
2308
            }
2309
 
2310
            // Get saholic stock for these items
2311
            Map<Integer, List<WarehouseItemQtyModel>> stockMap = saholicInventoryService.getSaholicStock(warehouseId, itemIds);
2312
 
2313
            // Build result with item description and qty where netAvailability > 0
2314
            List<Map<String, Object>> result = new ArrayList<>();
2315
            for (Item item : items) {
2316
                List<WarehouseItemQtyModel> stockList = stockMap.get(item.getId());
2317
                if (stockList != null && !stockList.isEmpty()) {
2318
                    int totalNetAvailability = stockList.stream()
2319
                            .mapToInt(WarehouseItemQtyModel::getNetAvailability)
2320
                            .sum();
2321
                    if (totalNetAvailability > 0) {
2322
                        Map<String, Object> itemDetail = new HashMap<>();
2323
                        itemDetail.put("itemId", item.getId());
2324
                        itemDetail.put("color", item.getColor());
2325
                        itemDetail.put("itemDescription", item.getItemDescription());
2326
                        itemDetail.put("qty", totalNetAvailability);
2327
                        result.add(itemDetail);
2328
                    }
2329
                }
2330
            }
2331
 
2332
            return responseSender.ok(result);
2333
        } catch (Exception e) {
2334
            LOGGER.error("Error getting our stock details for catalogId: {} warehouseId: {}", catalogId, warehouseId, e);
2335
            return responseSender.ok(Collections.emptyList());
2336
        }
2337
    }
2338
 
2339
    @RequestMapping(value = "/indent/getOutOfStockDetails", method = RequestMethod.GET)
35782 ranu 2340
    public ResponseEntity<?> getOutOfStockDetails(HttpServletRequest request, @RequestParam String brand, @RequestParam int warehouseId, @RequestParam int fofoId, Model model) throws Exception {
35765 ranu 2341
        try {
2342
            // Get all catalogs for the brand with their movement status
2343
            List<CategorisedCatalogListModel> catalogMovements = categorisedCatalogRepository.getBrandWiseCatalogMovement(brand);
2344
 
2345
            // Filter only HID, FASTMOVING, RUNNING status
2346
            Set<CatalogMovingEnum> validStatuses = new HashSet<>(Arrays.asList(
2347
                    CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING));
2348
 
2349
            List<CategorisedCatalogListModel> filteredCatalogs = catalogMovements.stream()
2350
                    .filter(c -> validStatuses.contains(c.getCurrentStatus()))
2351
                    .collect(Collectors.toList());
2352
 
2353
            if (filteredCatalogs.isEmpty()) {
2354
                return responseSender.ok(Collections.emptyList());
2355
            }
2356
 
35782 ranu 2357
            // Get all catalog IDs for partner stock lookup
2358
            Set<Integer> allCatalogIds = filteredCatalogs.stream()
2359
                    .map(CategorisedCatalogListModel::getModelId)
2360
                    .collect(Collectors.toSet());
2361
 
2362
            // Get partner stock for all catalogs - fetch all partner stock and map to catalog IDs
2363
            Map<Integer, Integer> partnerStockMap = new HashMap<>();
2364
            if (!allCatalogIds.isEmpty()) {
2365
                List<CurrentInventorySnapshot> partnerSnapshots = currentInventorySnapshotRepository.selectByFofoId(fofoId);
2366
                // Get item IDs from snapshots
2367
                Set<Integer> itemIds = partnerSnapshots.stream()
2368
                        .map(CurrentInventorySnapshot::getItemId)
2369
                        .collect(Collectors.toSet());
2370
                // Get items to map itemId -> catalogId
2371
                Map<Integer, Integer> itemToCatalogMap = new HashMap<>();
2372
                for (Integer itemId : itemIds) {
2373
                    Item item = itemRepository.selectById(itemId);
2374
                    if (item != null) {
2375
                        itemToCatalogMap.put(itemId, item.getCatalogItemId());
2376
                    }
2377
                }
2378
                // Group by catalog ID
2379
                for (CurrentInventorySnapshot snap : partnerSnapshots) {
2380
                    Integer catalogId = itemToCatalogMap.get(snap.getItemId());
2381
                    if (catalogId != null && allCatalogIds.contains(catalogId)) {
2382
                        partnerStockMap.merge(catalogId, snap.getAvailability(), Integer::sum);
2383
                    }
2384
                }
2385
            }
2386
 
2387
            // Get GRN pending orders for partner
2388
            Map<Integer, Integer> grnPendingMap = new HashMap<>();
2389
            List<Order> pendingGrnOrders = orderRepository.selectPendingGrnOrders(fofoId);
2390
            for (Order order : pendingGrnOrders) {
2391
                int itemId = order.getLineItem().getItemId();
2392
                Item item = itemRepository.selectById(itemId);
2393
                if (item != null && allCatalogIds.contains(item.getCatalogItemId())) {
2394
                    grnPendingMap.merge(item.getCatalogItemId(), order.getLineItem().getQuantity(), Integer::sum);
2395
                }
2396
            }
2397
 
2398
            // Get tag listings (DP prices) for all catalogs
2399
            List<Integer> catalogIdList = new ArrayList<>(allCatalogIds);
2400
            Map<Integer, TagListing> tagListingsMap = tagListingRepository.selectAllByCatalogIds(catalogIdList);
2401
 
35765 ranu 2402
            List<Map<String, Object>> result = new ArrayList<>();
2403
 
2404
            for (CategorisedCatalogListModel catalogModel : filteredCatalogs) {
2405
                int catalogId = catalogModel.getModelId();
2406
 
2407
                // Get all items for this catalog
2408
                List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
2409
                List<Integer> itemIds = items.stream().map(Item::getId).collect(Collectors.toList());
2410
 
35782 ranu 2411
                // Get DP price from tag listings
2412
                TagListing tagListing = tagListingsMap.get(catalogId);
2413
                double dpPrice = tagListing != null ? tagListing.getSellingPrice() : 0;
2414
 
35765 ranu 2415
                if (itemIds.isEmpty()) {
2416
                    // No items means out of stock for this model
2417
                    Map<String, Object> itemDetail = new HashMap<>();
2418
                    itemDetail.put("catalogId", catalogId);
2419
                    itemDetail.put("modelNumber", catalogModel.getModelNumber());
2420
                    itemDetail.put("status", catalogModel.getCurrentStatus().getValue());
2421
                    itemDetail.put("qty", 0);
35782 ranu 2422
                    itemDetail.put("partnerCurrentQty", partnerStockMap.getOrDefault(catalogId, 0) + grnPendingMap.getOrDefault(catalogId, 0));
2423
                    itemDetail.put("dp", dpPrice);
35765 ranu 2424
                    result.add(itemDetail);
2425
                    continue;
2426
                }
2427
 
2428
                // Get saholic stock for these items
2429
                Map<Integer, List<WarehouseItemQtyModel>> stockMap = saholicInventoryService.getSaholicStock(warehouseId, itemIds);
2430
 
2431
                // Calculate total net availability for this catalog
2432
                int totalNetAvailability = 0;
2433
                for (Item item : items) {
2434
                    List<WarehouseItemQtyModel> stockList = stockMap.get(item.getId());
2435
                    if (stockList != null && !stockList.isEmpty()) {
2436
                        totalNetAvailability += stockList.stream()
2437
                                .mapToInt(WarehouseItemQtyModel::getNetAvailability)
2438
                                .sum();
2439
                    }
2440
                }
2441
 
2442
                // Only include if out of stock (netAvailability <= 0)
2443
                if (totalNetAvailability <= 0) {
2444
                    Map<String, Object> itemDetail = new HashMap<>();
2445
                    itemDetail.put("catalogId", catalogId);
2446
                    itemDetail.put("modelNumber", catalogModel.getModelNumber());
2447
                    itemDetail.put("status", catalogModel.getCurrentStatus().getValue());
2448
                    itemDetail.put("qty", totalNetAvailability);
35782 ranu 2449
                    itemDetail.put("partnerCurrentQty", partnerStockMap.getOrDefault(catalogId, 0) + grnPendingMap.getOrDefault(catalogId, 0));
2450
                    itemDetail.put("dp", dpPrice);
35765 ranu 2451
                    result.add(itemDetail);
2452
                }
2453
            }
2454
 
2455
            return responseSender.ok(result);
2456
        } catch (Exception e) {
35782 ranu 2457
            LOGGER.error("Error getting out of stock details for brand: {} warehouseId: {} fofoId: {}", brand, warehouseId, fofoId, e);
35765 ranu 2458
            return responseSender.ok(Collections.emptyList());
2459
        }
2460
    }
2461
 
34580 ranu 2462
    @Autowired
2463
    FofoOpeningStockRepository fofoOpeningStockRepository;
34449 ranu 2464
 
34087 ranu 2465
    @RequestMapping(value = "/getPartnerShortageStock", method = RequestMethod.GET)
2466
    public String getPartnerShortageStock(HttpServletRequest request,
35011 ranu 2467
                                          @RequestParam(required = false, defaultValue = "") String brand, @RequestParam(required = false, defaultValue = "0") long shortInvest, @RequestParam(required = false, defaultValue = "0") long totalDueWithInterest, @RequestParam int fofoId, Model model)
34087 ranu 2468
            throws Exception {
2469
 
34384 ranu 2470
        LocalDateTime presentDate = LocalDateTime.now();
34397 ranu 2471
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
34384 ranu 2472
 
34035 ranu 2473
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
34087 ranu 2474
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
34035 ranu 2475
 
34581 ranu 2476
        int warehouseId = fofoStore.getWarehouseId();
2477
 
34389 ranu 2478
        List<BrandWisePartnerSaleModel> brandWisePartnerSaleModels = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(Arrays.asList(fofoId));
2479
        LOGGER.info("brandWisePartnerSaleModels {}", brandWisePartnerSaleModels);
2480
 
2481
        Map<String, Long> brandToMtdMap = brandWisePartnerSaleModels.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getMtd()));
2482
 
34397 ranu 2483
        Map<Integer, Double> secondaryMtd = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
2484
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
2485
                curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
2486
 
2487
        double purchaseMtd = secondaryMtd.getOrDefault(fofoId, 0.0);
2488
 
2489
        Map<Integer, Double> secondaryToday = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
2490
                Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
2491
                curDate, curDate.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
2492
 
2493
        double purchasedFtd = secondaryToday.getOrDefault(fofoId, 0.0);
2494
 
34412 ranu 2495
        MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
2496
 
34642 ranu 2497
        double purchaseTargetFtd = rbmTargetService.calculateFofoIdTodayTarget(fofoId, purchaseMtd, LocalDate.now());
34397 ranu 2498
 
2499
        double saleMtd = (Double) fofoUser.getSales(fofoId).get("mtdSale");
2500
 
2501
        double recoverableAmount = saleMtd - purchaseMtd;
2502
 
2503
        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(fofoId);
34412 ranu 2504
 
34397 ranu 2505
        UserWallet userWallet = walletService.getUserWallet(fofoId);
2506
 
34412 ranu 2507
        BigDecimal totalAvailableFunds = sdCreditRequirement.getAvailableLimit().add(BigDecimal.valueOf(userWallet.getAmount()));
34397 ranu 2508
 
2509
        List<Loan> loans = loanRepository.selectActiveLoan(fofoId);
34412 ranu 2510
        double totalPendingAmount = loans.stream()
2511
                .map(Loan::getPendingAmount)
2512
                .mapToDouble(BigDecimal::doubleValue)
2513
                .sum();
2514
 
34397 ranu 2515
        boolean isLoanPending = false;
2516
        if (loans.size() > 0) {
2517
            isLoanPending = true;
2518
        }
2519
 
34389 ranu 2520
 
34035 ranu 2521
        List<PartnerWarehouseStockSummaryModel> partnerWarehouseStockSummaryModels = saholicInventoryService.getSaholicAndPartnerStock(fofoId, fofoStore.getWarehouseId());
2522
 
34569 ranu 2523
        List<WarehouseIntransitDataModel> warehouseIntransitDataModels = saholicInventoryService.getWarehouseIntransistDataList().stream().filter((x -> x.getWarehouseId() == fofoStore.getWarehouseId())).collect(Collectors.toList());
2524
 
34589 ranu 2525
        Map<Integer, Long> catalogWiseQtyMap = new HashMap<>();
2526
        Set<Integer> inTransitCatalogIds = new HashSet<>();
2527
        List<PartnerWarehouseStockSummaryModel> intransistSummaryList = new ArrayList<>();
2528
        if (warehouseIntransitDataModels.size() > 0) {
2529
            Map<Integer, List<WarehouseIntransitDataModel>> warewarehouseIntransitDataModelsMap = warehouseIntransitDataModels.stream().collect(Collectors.groupingBy(WarehouseIntransitDataModel::getCatalogId));
34580 ranu 2530
 
34589 ranu 2531
            catalogWiseQtyMap = warehouseIntransitDataModels.stream()
2532
                    .collect(Collectors.groupingBy(
2533
                            WarehouseIntransitDataModel::getCatalogId,
2534
                            Collectors.summingLong(WarehouseIntransitDataModel::getQty)
2535
                    ));
34569 ranu 2536
 
34589 ranu 2537
            LOGGER.info("catalogWiseQtyMap key set {}", catalogWiseQtyMap.keySet());
34035 ranu 2538
 
34589 ranu 2539
            List<FofoOpeningStock> fofoOpeningStocksLitsForIntransist = fofoOpeningStockRepository.fofoOpeningStockByFofoId(catalogWiseQtyMap.keySet(), fofoId);
2540
            LOGGER.info("fofoOpeningStocksLitsForIntransist {}", fofoOpeningStocksLitsForIntransist);
2541
            // Optional: Build a map for faster lookup
2542
            Map<Integer, FofoOpeningStock> inTransistfofoOpeningStockMap = fofoOpeningStocksLitsForIntransist.stream()
2543
                    .collect(Collectors.toMap(FofoOpeningStock::getCatalogId, stock -> stock));
34437 ranu 2544
 
2545
 
34589 ranu 2546
            for (Map.Entry<Integer, Long> entry : catalogWiseQtyMap.entrySet()) {
2547
                int catalogId = entry.getKey();
2548
                long netAvailability = entry.getValue();
34580 ranu 2549
 
34589 ranu 2550
                FofoOpeningStock openingStock = inTransistfofoOpeningStockMap.get(catalogId);
2551
                WarehouseIntransitDataModel warehouseIntransitDataModel = warewarehouseIntransitDataModelsMap.get(catalogId).get(0);
34580 ranu 2552
 
34589 ranu 2553
                PartnerWarehouseStockSummaryModel inTransistmodel = new PartnerWarehouseStockSummaryModel(
2554
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getBrand() : "Unknown",
2555
                        catalogId,
2556
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getItemDescription() : "Unknown",
2557
                        warehouseIntransitDataModel != null ? 10006 : 0,
2558
                        (int) netAvailability,
2559
                        openingStock != null ? openingStock.getOpeningQty() : 0,
2560
                        openingStock != null ? openingStock.getCurrentQty() : 0,
2561
                        openingStock != null ? (openingStock.getOpeningQty() - openingStock.getCurrentQty()) : 0,
2562
                        warehouseIntransitDataModel != null ? warehouseIntransitDataModel.getStatus() : "Unknown"
2563
                );
34580 ranu 2564
 
34589 ranu 2565
                intransistSummaryList.add(inTransistmodel);
2566
            }
34580 ranu 2567
        }
2568
 
34589 ranu 2569
 
34490 ranu 2570
        List<DateWiseSoldCatalogQtyModel> sevenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(7));
34384 ranu 2571
 
34490 ranu 2572
        List<DateWiseSoldCatalogQtyModel> fourteenDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(14));
34384 ranu 2573
 
34490 ranu 2574
        List<DateWiseSoldCatalogQtyModel> twentyOneDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(21));
34412 ranu 2575
 
34384 ranu 2576
        LOGGER.info("twentyOneDayAboveSoldsCatalogs {}", twentyOneDayAboveSoldsCatalogs);
34412 ranu 2577
 
34490 ranu 2578
        List<DateWiseSoldCatalogQtyModel> twentyEightDayAboveSoldsCatalogs = fofoOrderRepository.getDateWiseSoldCatalogQty(fofoId, presentDate.minusDays(28));
34384 ranu 2579
 
34580 ranu 2580
        Set<Integer> catalogIds = partnerWarehouseStockSummaryModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
34412 ranu 2581
 
34589 ranu 2582
        if (!catalogWiseQtyMap.isEmpty()) {
2583
            inTransitCatalogIds = catalogWiseQtyMap.keySet().stream().filter(catalogId -> !catalogIds.contains(catalogId)).collect(Collectors.toSet());
2584
        }
34580 ranu 2585
 
2586
        // Add the missing IDs to the original set
2587
        catalogIds.addAll(inTransitCatalogIds);
2588
 
2589
        List<Integer> catalogsList = new ArrayList<>(catalogIds);
2590
 
37389 ranu 2591
        Map<Integer, TagListing> tagListingsMap = catalogsList.isEmpty()
2592
                ? Collections.emptyMap()
2593
                : tagListingRepository.selectAllByCatalogIds(catalogsList);
34580 ranu 2594
 
37390 ranu 2595
        List<CatalogAgingModel> catalogAgingModels = catalogIds.isEmpty()
2596
                ? Collections.emptyList()
2597
                : ageingService.getCatalogsAgingByWarehouse(catalogIds, fofoStore.getWarehouseId());
34035 ranu 2598
 
2599
        Map<Integer, CatalogAgingModel> catalogAgingModelMap = catalogAgingModels.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
2600
 
2601
        List<PartnerWarehouseStockAgingSummaryModel> partnerWarehouseStockAgingSummaryModelList = new ArrayList<>();
2602
 
37055 ranu 2603
        // Tier-aware floor for P-Fullfilled: partners must always be suggested
2604
        // at least a minimum quantity per SKU based on their tier. If the raw
2605
        // opening_qty from fofo_opening_stock is below the floor, we show the
2606
        // floor instead (this also gives red rows / never-held SKUs a real
2607
        // number to act on). P-Shortage is recomputed against the effective
2608
        // P-Fullfilled so the two columns stay consistent.
2609
        //   GOLD / NEW / (fallback)    → 3
2610
        //   DIAMOND / PLATINUM         → 5
2611
        //   SILVER / BRONZE            → 2
2612
        int tierFloor;
2613
        PartnerTypeChange partnerTypeChangeForFloor = partnerTypeChangeRepository.getRecentChange(fofoId, LocalDate.now());
2614
        PartnerType partnerTierForFloor = partnerTypeChangeForFloor != null ? partnerTypeChangeForFloor.getPartnerType() : null;
2615
        if (partnerTierForFloor == PartnerType.DIAMOND || partnerTierForFloor == PartnerType.PLATINUM) {
2616
            tierFloor = 5;
2617
        } else if (partnerTierForFloor == PartnerType.SILVER || partnerTierForFloor == PartnerType.BRONZE) {
2618
            tierFloor = 2;
2619
        } else {
2620
            tierFloor = 3;
2621
        }
2622
 
34035 ranu 2623
        for (PartnerWarehouseStockSummaryModel stockSummary : partnerWarehouseStockSummaryModels) {
2624
 
2625
            PartnerWarehouseStockAgingSummaryModel partnerWarehouseStockAgingSummaryModel = new PartnerWarehouseStockAgingSummaryModel();
2626
            partnerWarehouseStockAgingSummaryModel.setCatalogId(stockSummary.getCatalogId());
2627
            partnerWarehouseStockAgingSummaryModel.setBrand(stockSummary.getBrand());
2628
            partnerWarehouseStockAgingSummaryModel.setModelNumber(stockSummary.getModelNumber());
2629
            partnerWarehouseStockAgingSummaryModel.setNetAvailability(stockSummary.getShaholicNetAvailability());
37055 ranu 2630
            int effectivePFullfilled = Math.max(stockSummary.getPartnerFullFilledQty(), tierFloor);
2631
            int currentQty = stockSummary.getPartnerCurrentQty();
2632
            partnerWarehouseStockAgingSummaryModel.setPartnerStockAvailability(effectivePFullfilled);
2633
            partnerWarehouseStockAgingSummaryModel.setPartnerCurrentAvailability(currentQty);
2634
            partnerWarehouseStockAgingSummaryModel.setPartnerShortageStock(Math.max(effectivePFullfilled - currentQty, 0));
34472 ranu 2635
            if (catalogAgingModelMap.get(stockSummary.getCatalogId()) != null) {
2636
                partnerWarehouseStockAgingSummaryModel.setExceedDays(catalogAgingModelMap.get(stockSummary.getCatalogId()).getExceedDays());
34489 ranu 2637
            } else {
2638
                partnerWarehouseStockAgingSummaryModel.setExceedDays(0);
2639
 
34472 ranu 2640
            }
34035 ranu 2641
            partnerWarehouseStockAgingSummaryModel.setStatus(stockSummary.getStatus());
2642
 
2643
            partnerWarehouseStockAgingSummaryModelList.add(partnerWarehouseStockAgingSummaryModel);
2644
        }
2645
 
34580 ranu 2646
        Set<Integer> existingCatalogIdsInAgingSummaryList = partnerWarehouseStockAgingSummaryModelList.stream()
2647
                .map(PartnerWarehouseStockAgingSummaryModel::getCatalogId)
2648
                .collect(Collectors.toSet());
34389 ranu 2649
 
34589 ranu 2650
        if (intransistSummaryList.size() > 0) {
2651
            // Step 2: Iterate over intransitSummaryList and add missing ones
2652
            for (PartnerWarehouseStockSummaryModel intransitStock : intransistSummaryList) {
2653
                if (!existingCatalogIdsInAgingSummaryList.contains(intransitStock.getCatalogId())) {
2654
                    PartnerWarehouseStockAgingSummaryModel agingModel = new PartnerWarehouseStockAgingSummaryModel();
2655
                    agingModel.setCatalogId(intransitStock.getCatalogId());
2656
                    agingModel.setBrand(intransitStock.getBrand());
2657
                    agingModel.setModelNumber(intransitStock.getModelNumber());
2658
                    agingModel.setNetAvailability(0); // Not part of original aging summary
37055 ranu 2659
                    int intransitEffectivePFullfilled = Math.max(intransitStock.getPartnerFullFilledQty(), tierFloor);
2660
                    int intransitCurrentQty = intransitStock.getPartnerCurrentQty();
2661
                    agingModel.setPartnerStockAvailability(intransitEffectivePFullfilled);
2662
                    agingModel.setPartnerCurrentAvailability(intransitCurrentQty);
2663
                    agingModel.setPartnerShortageStock(Math.max(intransitEffectivePFullfilled - intransitCurrentQty, 0));
34589 ranu 2664
                    if (catalogAgingModelMap.get(intransitStock.getCatalogId()) != null) {
2665
                        agingModel.setExceedDays(catalogAgingModelMap.get(intransitStock.getCatalogId()).getExceedDays());
2666
                    } else {
2667
                        agingModel.setExceedDays(0);
2668
                    }
2669
                    agingModel.setStatus(intransitStock.getStatus() == null ? "OTHER" : intransitStock.getStatus());
2670
 
2671
                    partnerWarehouseStockAgingSummaryModelList.add(agingModel);
34580 ranu 2672
                }
2673
            }
2674
        }
2675
 
2676
 
34384 ranu 2677
        List<String> statusOrder = Arrays.asList("HID", "FASTMOVING", "RUNNING", "SLOWMOVING", "OTHER");
34035 ranu 2678
 
2679
        Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> brandStatusWiseStockListMap =
2680
                partnerWarehouseStockAgingSummaryModelList.stream().collect(Collectors.groupingBy(
2681
                        PartnerWarehouseStockAgingSummaryModel::getBrand,
2682
                        Collectors.groupingBy(PartnerWarehouseStockAgingSummaryModel::getStatus)
2683
                ));
34389 ranu 2684
//map of list as hid,fast,slow and other in last otherwise other is coming in start (here is using status order)
35782 ranu 2685
        // Also sort items alphabetically by model number within each status group
34035 ranu 2686
        Map<String, Map<String, List<PartnerWarehouseStockAgingSummaryModel>>> sortedBrandStatusWiseStockListMap =
2687
                brandStatusWiseStockListMap.entrySet().stream().collect(Collectors.toMap(
2688
                        Map.Entry::getKey, // Key (Brand)
2689
                        entry -> {
2690
                            Map<String, List<PartnerWarehouseStockAgingSummaryModel>> sortedStatusMap = entry.getValue().entrySet().stream()
2691
                                    .sorted((e1, e2) -> Integer.compare(
2692
                                            statusOrder.indexOf(e1.getKey()),
2693
                                            statusOrder.indexOf(e2.getKey())
2694
                                    ))
2695
                                    .collect(Collectors.toMap(
2696
                                            Map.Entry::getKey,
35782 ranu 2697
                                            e -> e.getValue().stream()
2698
                                                    .sorted(Comparator.comparing(PartnerWarehouseStockAgingSummaryModel::getModelNumber, String.CASE_INSENSITIVE_ORDER))
2699
                                                    .collect(Collectors.toList()),
34035 ranu 2700
                                            (v1, v2) -> v1,
2701
                                            LinkedHashMap::new // Ensure ordering is maintained
2702
                                    ));
2703
                            return sortedStatusMap;
2704
                        },
2705
                        (v1, v2) -> v1,
2706
                        LinkedHashMap::new // Maintain order of brands
2707
                ));
34490 ranu 2708
        LOGGER.info("brandToMtdMap {}", brandToMtdMap);
34454 ranu 2709
        List<String> sortedBrandsByMtd = brandToMtdMap.entrySet()
2710
                .stream()
2711
                .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // Descending MTD
2712
                .map(Map.Entry::getKey)
2713
                .collect(Collectors.toList());
2714
 
2715
        List<String> remainingBrands = ProfitMandiConstants.BRANDS.stream()
2716
                .filter(x -> !brandToMtdMap.containsKey(x))
2717
                .filter(x -> sortedBrandStatusWiseStockListMap.containsKey(x))
2718
                .collect(Collectors.toList());
2719
        List<String> remainingBrandsWithoutStock = ProfitMandiConstants.BRANDS.stream()
2720
                .filter(x -> !brandToMtdMap.containsKey(x))
2721
                .filter(x -> !sortedBrandStatusWiseStockListMap.containsKey(x)) // no stock
2722
                .collect(Collectors.toList());
2723
 
34683 ranu 2724
        List<InStockBrandItemModel> inStockBrandItemModels = currentInventorySnapshotRepository.selectInStockItemsByBrand(fofoId);
2725
 
2726
        Map<String, Long> brandsWithPartnerStockMap = inStockBrandItemModels.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand, Collectors.summingLong(InStockBrandItemModel::getQty)));
2727
        List<String> brandsWithPartnerStock = brandsWithPartnerStockMap.entrySet().stream().filter(x -> x.getValue() > 0).map(x -> x.getKey()).collect(Collectors.toList());
34513 ranu 2728
        List<String> sortedBrands = new ArrayList<>();
2729
        sortedBrands.addAll(sortedBrandsByMtd);
2730
        sortedBrands.addAll(remainingBrands);
2731
        sortedBrands.addAll(remainingBrandsWithoutStock);
34454 ranu 2732
 
34513 ranu 2733
        List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
2734
 
2735
        List<String> finalSortedBrands = sortedBrands.stream().filter(x -> !partnerIneligibleBrands.contains(x) && !"itel".equalsIgnoreCase(x)).collect(Collectors.toList());
2736
 
34487 ranu 2737
        Map<Integer, Integer> processingOrderMap = null;
2738
        List<PartnerStockDetailModel> pendingIndents = new ArrayList<>();
2739
        Map<Integer, PartnerStockDetailModel> pendingIndentsDetailMap = new HashMap<>();
2740
 
2741
        Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
2742
                .collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
2743
                        Collectors.summingInt(x -> x.getLineItem().getQuantity())));
2744
        if (!processingOrder.isEmpty()) {
2745
            processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
2746
                    .collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
2747
                            Collectors.summingInt(x -> processingOrder.get(x.getId()))));
2748
            pendingIndents.addAll(getBrandItemwiseDetail(brand, processingOrderMap));
2749
            pendingIndentsDetailMap = pendingIndents.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
2750
 
2751
        }
2752
        LOGGER.info("pendingIndents {}", pendingIndents);
2753
        LOGGER.info("pendingIndentsDetailMap {}", pendingIndentsDetailMap);
2754
 
34035 ranu 2755
        model.addAttribute("brandStatusWiseStockListMap", sortedBrandStatusWiseStockListMap);
34683 ranu 2756
        model.addAttribute("brandsWithPartnerStock", brandsWithPartnerStock);
34487 ranu 2757
        model.addAttribute("pendingIndentsDetailMap", pendingIndentsDetailMap);
34412 ranu 2758
        model.addAttribute("brands", finalSortedBrands);
2759
        model.addAttribute("brandToMtdMap", brandToMtdMap);
34569 ranu 2760
        model.addAttribute("catalogWiseQtyMap", catalogWiseQtyMap);
34580 ranu 2761
        model.addAttribute("intransistSummaryList", intransistSummaryList);
34087 ranu 2762
        model.addAttribute("brand", brand);
2763
        model.addAttribute("fofoId", fofoId);
34581 ranu 2764
        model.addAttribute("warehouseId", warehouseId);
34087 ranu 2765
        model.addAttribute("customRetailer", customRetailer);
34397 ranu 2766
        model.addAttribute("shortInvest", shortInvest);
35011 ranu 2767
        model.addAttribute("totalDueWithInterest", totalDueWithInterest);
35771 ranu 2768
        model.addAttribute("interestDue", Math.subtractExact(totalDueWithInterest, sdCreditRequirement.getUtilizedAmount().intValue()));
2769
 
34397 ranu 2770
        model.addAttribute("purchaseMtd", purchaseMtd);
2771
        model.addAttribute("purchasedFtd", purchasedFtd);
2772
        model.addAttribute("saleMtd", saleMtd);
2773
        model.addAttribute("purchaseTargetFtd", purchaseTargetFtd);
2774
        model.addAttribute("recoverableAmount", recoverableAmount);
2775
        model.addAttribute("isLoanPending", isLoanPending);
2776
        model.addAttribute("totalAvailableFunds", totalAvailableFunds);
34412 ranu 2777
        model.addAttribute("sdCreditRequirement", sdCreditRequirement);
2778
        model.addAttribute("userWallet", userWallet);
2779
        model.addAttribute("monthlyTarget", monthlyTarget);
2780
        model.addAttribute("totalPendingAmount", totalPendingAmount);
34437 ranu 2781
        model.addAttribute("tagListingsMap", tagListingsMap);
34412 ranu 2782
        model.addAttribute("sevenDayAboveSoldsCatalogs", sevenDayAboveSoldsCatalogs);
2783
        model.addAttribute("fourteenDayAboveSoldsCatalogs", fourteenDayAboveSoldsCatalogs);
2784
        model.addAttribute("twentyOneDayAboveSoldsCatalogs", twentyOneDayAboveSoldsCatalogs);
2785
        model.addAttribute("twentyEightDayAboveSoldsCatalogs", twentyEightDayAboveSoldsCatalogs);
32839 amit.gupta 2786
        return "partner-stock";
30003 tejbeer 2787
 
32839 amit.gupta 2788
    }
30044 tejbeer 2789
 
32839 amit.gupta 2790
    private List<PartnerStockDescriptionModel> getBrandItemwiseDescription(String brand,
2791
                                                                           Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
2792
        List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();
30044 tejbeer 2793
 
32839 amit.gupta 2794
        for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2795
            List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
30044 tejbeer 2796
 
32839 amit.gupta 2797
            if (brand.equals("accessories")) {
2798
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
30044 tejbeer 2799
 
32839 amit.gupta 2800
                    if (items.get(0).getCategoryId() != 0) {
2801
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30044 tejbeer 2802
 
32839 amit.gupta 2803
                        if (category.getParentCategoryId() == 10011) {
2804
                            PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2805
                            psdp.setBrand(items.get(0).getBrand());
2806
                            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2807
                                    + items.get(0).getModelNumber());
2808
                            psdp.setQty(inStock.getValue());
2809
                            inStocks.add(psdp);
2810
                        }
2811
                    }
30044 tejbeer 2812
 
32839 amit.gupta 2813
                }
30044 tejbeer 2814
 
32839 amit.gupta 2815
            } else if (brand.equals("TV")) {
2816
                if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
30044 tejbeer 2817
 
32839 amit.gupta 2818
                    if (items.get(0).getCategoryId() != 0) {
2819
                        Category category = categoryRepository.selectById(items.get(0).getCategoryId());
30044 tejbeer 2820
 
32839 amit.gupta 2821
                        if (category.getParentCategoryId() == 14200) {
2822
                            PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2823
                            psdp.setBrand(items.get(0).getBrand());
2824
                            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2825
                                    + items.get(0).getModelNumber());
2826
                            psdp.setQty(inStock.getValue());
2827
                            inStocks.add(psdp);
2828
                        }
2829
                    }
30044 tejbeer 2830
 
32839 amit.gupta 2831
                }
30044 tejbeer 2832
 
32839 amit.gupta 2833
            } else {
2834
                PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2835
                psdp.setBrand(items.get(0).getBrand());
2836
                psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2837
                        + items.get(0).getModelNumber());
2838
                psdp.setQty(inStock.getValue());
2839
                inStocks.add(psdp);
2840
            }
30044 tejbeer 2841
 
32839 amit.gupta 2842
        }
30044 tejbeer 2843
 
32839 amit.gupta 2844
        return inStocks;
2845
    }
30003 tejbeer 2846
 
34487 ranu 2847
    private List<PartnerStockDetailModel> getBrandItemwiseDetail(String brand,
2848
                                                                 Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
2849
        List<PartnerStockDetailModel> inStocks = new ArrayList<>();
2850
 
2851
        for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2852
            List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
2853
            PartnerStockDetailModel psdp = new PartnerStockDetailModel();
2854
            psdp.setBrand(items.get(0).getBrand());
2855
            psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2856
                    + items.get(0).getModelNumber());
2857
            psdp.setQty(inStock.getValue());
2858
            psdp.setCatalogId(items.get(0).getCatalogItemId());
2859
            inStocks.add(psdp);
2860
        }
2861
 
2862
        return inStocks;
2863
    }
2864
 
32839 amit.gupta 2865
    private FocusedModelShortageModel getFocusedModelShortage(int qty, int catalogId,
2866
                                                              Map<Integer, Integer> processingOrderMap, Map<Integer, Integer> grnPendingOrdersMap,
2867
                                                              Map<Integer, Integer> catalogIdAndQtyMap, int fofoId,
2868
                                                              Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap, List<Item> items,
2869
                                                              CustomRetailer customRetailer) throws ProfitMandiBusinessException {
30003 tejbeer 2870
 
32839 amit.gupta 2871
        int minQty = qty;
2872
        int inStockQty = 0;
2873
        int processingQty = 0;
2874
        int grnPendingQty = 0;
2875
        int allColorNetAvailability = 0;
2876
        int allColorPoAvailability = 0;
2877
        if (processingOrderMap != null) {
2878
            processingQty = (processingOrderMap.get(catalogId) == null) ? 0 : processingOrderMap.get(catalogId);
30003 tejbeer 2879
 
32839 amit.gupta 2880
        }
2881
        if (grnPendingOrdersMap != null) {
2882
            grnPendingQty = (grnPendingOrdersMap.get(catalogId) == null) ? 0 : grnPendingOrdersMap.get(catalogId);
30003 tejbeer 2883
 
32839 amit.gupta 2884
        }
2885
        if (catalogIdAndQtyMap != null) {
2886
            inStockQty = (catalogIdAndQtyMap.get(catalogId) == null) ? 0 : catalogIdAndQtyMap.get(catalogId);
30003 tejbeer 2887
 
32839 amit.gupta 2888
        }
30003 tejbeer 2889
 
32839 amit.gupta 2890
        int grnStockQty = grnPendingQty + inStockQty;
2891
        int totalQty = processingQty + grnPendingQty + inStockQty;
30003 tejbeer 2892
 
32839 amit.gupta 2893
        int shortageQty = minQty - totalQty;
2894
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
30003 tejbeer 2895
 
32839 amit.gupta 2896
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap
2897
                .get(fofoStore.getWarehouseId());
30003 tejbeer 2898
 
32839 amit.gupta 2899
        for (Item it : items) {
2900
            List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(it.getId(),
2901
                    fofoStore.getWarehouseId());
2902
            List<SaholicPOItem> poItemAvailability = null;
30003 tejbeer 2903
 
32839 amit.gupta 2904
            if (poItemAvailabilityMap != null) {
2905
                poItemAvailability = poItemAvailabilityMap.get(it.getId());
2906
            }
2907
            if (currentAvailability != null) {
2908
                allColorNetAvailability += currentAvailability.stream()
2909
                        .collect(Collectors.summingInt(SaholicCISTable::getNetAvailability));
2910
            }
30003 tejbeer 2911
 
32839 amit.gupta 2912
            if (poItemAvailability != null) {
2913
                allColorPoAvailability += poItemAvailability.stream()
2914
                        .collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
2915
            }
30003 tejbeer 2916
 
32839 amit.gupta 2917
        }
30003 tejbeer 2918
 
32839 amit.gupta 2919
        FocusedModelShortageModel fm = new FocusedModelShortageModel();
2920
        fm.setFofoId(fofoId);
2921
        fm.setStoreCode(fofoStore.getCode());
2922
        fm.setStoreName(customRetailer.getBusinessName());
2923
        fm.setBrandName(items.get(0).getBrand());
2924
        fm.setModelName(items.get(0).getModelName());
2925
        fm.setModelNumber(items.get(0).getModelNumber());
2926
        fm.setGrnStockQty(grnStockQty);
2927
        fm.setPendingIndentQty(processingQty);
2928
        fm.setShortageQty(shortageQty);
2929
        fm.setPoAvailability(allColorPoAvailability);
2930
        fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
2931
        fm.setAvailability(allColorNetAvailability);
2932
        return fm;
30003 tejbeer 2933
 
32839 amit.gupta 2934
    }
30017 amit.gupta 2935
 
32839 amit.gupta 2936
    @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.GET)
2937
    public String SendPONotification(HttpServletRequest request, Model model) {
37846 amit 2938
        model.addAttribute("warehouses", billingWarehouseService.getActiveWarehouses());
32839 amit.gupta 2939
        return "send-po-notification";
2940
    }
30017 amit.gupta 2941
 
32839 amit.gupta 2942
    @RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.POST)
2943
    public String sendPONotification(HttpServletRequest request, @RequestBody POItemWarehouseModel poItemWarehouseModel,
2944
                                     Model model) throws Exception {
30017 amit.gupta 2945
 
32839 amit.gupta 2946
        Map<Integer, Item> selectedCatalogItemMap = itemRepository
2947
                .selectAllByCatalogIds(new HashSet<>(poItemWarehouseModel.getCatalogIds())).stream()
2948
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x, (existing, replacement) -> existing));
30080 amit.gupta 2949
 
32839 amit.gupta 2950
        Set<String> brands = selectedCatalogItemMap.values().stream().map(x -> x.getBrand().toLowerCase())
2951
                .collect(Collectors.toSet());
30017 amit.gupta 2952
 
32839 amit.gupta 2953
        int warehouseId = poItemWarehouseModel.getWarehouseId();
2954
        for (String brand : brands) {
2955
            List<String> modelNames = selectedCatalogItemMap.entrySet().stream()
2956
                    .filter(x -> x.getValue().getBrand().toLowerCase().equals(brand))
2957
                    .map(x -> x.getValue().getItemDescriptionNoColor()).collect(Collectors.toList());
2958
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
2959
            sendNotificationModel.setCampaignName("SendPo");
2960
            sendNotificationModel.setTitle(String.format(PO_TITLE_STRING));
2961
            sendNotificationModel.setMessage(String.join(", ", modelNames));
2962
            sendNotificationModel.setType("url");
2963
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
2964
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2965
            sendNotificationModel.setMessageType(MessageType.notification);
30017 amit.gupta 2966
 
32839 amit.gupta 2967
            List<BrandRegionMapping> brandRegionMappings = brandRegionMappingRepository.selectAll().stream()
2968
                    .filter(x -> brand.equals(x.getBrand().toLowerCase()) && x.getFromWarehouseId() == warehouseId
2969
                            && !x.isAccessory())
2970
                    .collect(Collectors.toList());
2971
            List<Integer> toWarehouseIds = brandRegionMappings.stream().map(x -> x.getToWarehouseId())
2972
                    .collect(Collectors.toList());
30017 amit.gupta 2973
 
32839 amit.gupta 2974
            List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(toWarehouseIds).stream()
2975
                    .filter(x -> !x.isInternal() && x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
30017 amit.gupta 2976
 
32839 amit.gupta 2977
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
2978
            sendNotificationModel.setUserIds(userIds);
2979
            notificationService.sendNotification(sendNotificationModel);
2980
        }
2981
        model.addAttribute("response1", true);
2982
        return "response";
2983
    }
2984
 
25721 tejbeer 2985
}