Subversion Repositories SmartDukaan

Rev

Rev 36985 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
23819 govind 1
package com.spice.profitmandi.web.controller;
2
 
23945 amit.gupta 3
import com.fasterxml.jackson.databind.ObjectMapper;
29926 amit.gupta 4
import com.spice.profitmandi.common.enumuration.MessageType;
23819 govind 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
29926 amit.gupta 6
import com.spice.profitmandi.common.model.*;
23945 amit.gupta 7
import com.spice.profitmandi.common.services.ReporticoService;
23951 amit.gupta 8
import com.spice.profitmandi.common.util.FileUtil;
23945 amit.gupta 9
import com.spice.profitmandi.common.util.FormattingUtils;
28102 tejbeer 10
import com.spice.profitmandi.common.util.Utils;
23819 govind 11
import com.spice.profitmandi.dao.entity.catalog.Item;
23884 amit.gupta 12
import com.spice.profitmandi.dao.entity.catalog.TagListing;
32905 shampa 13
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
24822 amit.gupta 14
import com.spice.profitmandi.dao.entity.inventory.ItemPricingHistory;
23884 amit.gupta 15
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
23819 govind 16
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
24083 amit.gupta 17
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
31903 amit.gupta 18
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
24083 amit.gupta 19
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
31903 amit.gupta 20
import com.spice.profitmandi.dao.model.AmountModel;
23819 govind 21
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23884 amit.gupta 22
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
35547 amit 23
import com.spice.profitmandi.dao.event.TagListingEventPublisher;
29926 amit.gupta 24
import com.spice.profitmandi.dao.repository.cs.CsService;
28136 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
28102 tejbeer 26
import com.spice.profitmandi.dao.repository.dtr.Mongo;
29926 amit.gupta 27
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
28102 tejbeer 28
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
24822 amit.gupta 29
import com.spice.profitmandi.dao.repository.inventory.ItemPricingHistoryRepository;
23884 amit.gupta 30
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
23983 amit.gupta 31
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
24083 amit.gupta 32
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
23819 govind 33
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
29926 amit.gupta 34
import com.spice.profitmandi.service.NotificationService;
29951 amit.gupta 35
import com.spice.profitmandi.service.authentication.RoleManager;
32844 shampa 36
import com.spice.profitmandi.service.catalog.BrandsService;
23819 govind 37
import com.spice.profitmandi.service.inventory.InventoryService;
34651 aman.kumar 38
import com.spice.profitmandi.service.order.OrderService;
31903 amit.gupta 39
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModelNew;
29788 amit.gupta 40
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
41
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
23983 amit.gupta 42
import com.spice.profitmandi.service.pricing.PriceDropService;
37000 amit 43
import com.spice.profitmandi.service.pricing.PriceHikeService;
23968 amit.gupta 44
import com.spice.profitmandi.service.scheme.SchemeService;
23884 amit.gupta 45
import com.spice.profitmandi.service.transaction.TransactionService;
28102 tejbeer 46
import com.spice.profitmandi.service.user.RetailerService;
23819 govind 47
import com.spice.profitmandi.service.wallet.WalletService;
28102 tejbeer 48
import com.spice.profitmandi.web.model.LoginDetails;
49
import com.spice.profitmandi.web.util.CookiesProcessor;
23819 govind 50
import com.spice.profitmandi.web.util.MVCResponseSender;
29926 amit.gupta 51
import org.apache.commons.io.output.ByteArrayOutputStream;
52
import org.apache.logging.log4j.LogManager;
53
import org.apache.logging.log4j.Logger;
54
import org.springframework.beans.factory.annotation.Autowired;
55
import org.springframework.beans.factory.annotation.Qualifier;
56
import org.springframework.core.io.ByteArrayResource;
57
import org.springframework.http.HttpHeaders;
58
import org.springframework.http.HttpStatus;
59
import org.springframework.http.ResponseEntity;
60
import org.springframework.stereotype.Controller;
61
import org.springframework.transaction.annotation.Transactional;
62
import org.springframework.ui.Model;
63
import org.springframework.web.bind.annotation.*;
23819 govind 64
 
29926 amit.gupta 65
import javax.servlet.http.HttpServletRequest;
66
import java.io.Serializable;
67
import java.time.LocalDate;
68
import java.time.LocalDateTime;
69
import java.util.*;
70
import java.util.stream.Collectors;
71
 
23819 govind 72
@Controller
27071 amit.gupta 73
@Transactional(rollbackFor = Throwable.class)
23819 govind 74
public class PriceDropController {
75
 
31903 amit.gupta 76
    private static final Logger LOGGER = LogManager.getLogger(PriceDropController.class);
34317 amit.gupta 77
    /*private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin", "Modelwise");
31910 amit.gupta 78
    private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support", "Sellout Support");
34317 amit.gupta 79
    private static final List<String> ALL_MARGINS = Arrays.asList(SELLINS, SELLOUTS).stream().flatMap(x -> x.stream()).collect(Collectors.toList());*/
31903 amit.gupta 80
    @Autowired
81
    ReporticoService reporticoService;
82
    @Autowired
83
    LineItemImeisRepository lineItemImeisRepository;
84
    @Autowired
85
    PriceCircularService priceCircularService;
86
    @Autowired
87
    private CsService csService;
88
    @Autowired
89
    private UserRepository dtrUserRepository;
90
    @Autowired
91
    private PriceDropRepository priceDropRepository;
92
    @Autowired
93
    private ObjectMapper objectMapper;
94
    @Autowired
95
    private VendorItemPricingRepository vendorItemPricingRepository;
96
    @Autowired
97
    @Qualifier("fofoInventoryService")
98
    private InventoryService inventoryService;
99
    @Autowired
100
    private MVCResponseSender mvcResponseSender;
101
    @Autowired
102
    private PriceDropService priceDropService;
103
    @Autowired
37000 amit 104
    private PriceHikeService priceHikeService;
105
    @Autowired
31903 amit.gupta 106
    private ItemPricingHistoryRepository itemPricingHistoryRepository;
107
    @Autowired
108
    private WalletService walletService;
109
    @Autowired
110
    private TagListingRepository tagListingRepository;
111
    @Autowired
112
    private TransactionService transactionService;
113
    @Autowired
114
    private PriceDropIMEIRepository priceDropIMEIRepository;
115
    @Autowired
116
    private RoleManager roleManager;
117
    @Autowired
118
    @Qualifier("catalogItemRepository")
119
    private ItemRepository itemRepository;
120
    @Autowired
121
    private SchemeService schemeService;
122
    @Autowired
123
    private Mongo mongoClient;
124
    @Autowired
125
    private CookiesProcessor cookiesProcessor;
126
    @Autowired
127
    private PartnerTypeChangeService partnerTypeChangeService;
128
    @Autowired
129
    private RetailerService retailerService;
130
    @Autowired
131
    private NotificationService notificationService;
132
    @Autowired
133
    private FofoStoreRepository fofoStoreRepository;
23819 govind 134
 
34651 aman.kumar 135
    @Autowired
136
    OrderService orderService;
137
 
35547 amit 138
    @Autowired
139
    private TagListingEventPublisher tagListingEventPublisher;
140
 
31903 amit.gupta 141
    @RequestMapping(value = "/getItemDescription", method = RequestMethod.GET)
142
    public String getItemDescription(HttpServletRequest request, Model model) throws Throwable {
143
        List<PriceDrop> priceDrops = priceDropRepository.selectAllIncomplete();
144
        Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
29926 amit.gupta 145
 
31903 amit.gupta 146
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
147
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
148
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
149
        model.addAttribute("priceDrops", priceDrops);
150
        model.addAttribute("catalogDescription", catalogDescription);
151
        return "price-drop";
152
    }
29926 amit.gupta 153
 
34651 aman.kumar 154
    @RequestMapping(value = "/getPricedropByDate", method = RequestMethod.GET)
155
    public String getItemDescriptionByDate(
156
            HttpServletRequest request,
157
            @RequestParam LocalDateTime startDate,
158
            @RequestParam LocalDateTime endDate,
159
            Model model) throws Throwable {
34657 aman.kumar 160
        if (endDate.isAfter(LocalDateTime.now().plusDays(1)) || startDate.isAfter(LocalDateTime.now().plusDays(1))) {
34651 aman.kumar 161
            throw new ProfitMandiBusinessException("startData and end data must if before the today date ", "", "");
162
        }
163
        try {
164
            List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetweenSortByDate(startDate, endDate);
165
 
166
            Set<Integer> catalogIds = priceDrops.stream()
167
                    .map(PriceDrop::getCatalogItemId)
168
                    .collect(Collectors.toSet());
169
 
170
            List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
171
            Map<Integer, String> catalogDescription = items.stream()
172
                    .collect(Collectors.toMap(
173
                            Item::getCatalogItemId,
174
                            Item::getItemDescriptionNoColor,
175
                            (description1, description2) -> description1));
176
 
177
            model.addAttribute("priceDrops", priceDrops);
178
            model.addAttribute("catalogDescription", catalogDescription);
179
 
180
            return "price-drop-table";
181
 
182
        } catch (Exception e) {
183
            e.printStackTrace();
184
            return "price-drop";
185
        }
186
    }
187
    @RequestMapping(value = "/pricedropByDate/download", method = RequestMethod.GET)
188
    public ResponseEntity<?> dowloadItems(HttpServletRequest request, @PathVariable(name = "tagId") @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate)
189
            throws Throwable {
190
        List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetweenSortByDate(startDate, endDate);
191
        Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
192
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
193
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
194
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
195
 
196
        List<List<?>> rows = new ArrayList<>();
197
        for (PriceDrop priceDrop : priceDrops) {
34720 aman.kumar 198
            rows.add(Arrays.asList(priceDrop.getId(), priceDrop.getCatalogItemId(), catalogDescription.get(priceDrop.getCatalogItemId()), priceDrop.getTp(), priceDrop.getOldDp(), priceDrop.getMop(),
34657 aman.kumar 199
                    priceDrop.getAmount(), priceDrop.getNewDp(), FormattingUtils.formatDate(priceDrop.getAffectedOn()), FormattingUtils.formatDate(priceDrop.getCreatedOn())
34651 aman.kumar 200
            ));
201
 
202
        }
203
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
34720 aman.kumar 204
                Arrays.asList("Drop Id", "Catalog Id", "Item Name", "TP", "DP", "Mop", "Price Drop",
34651 aman.kumar 205
                        "New DP", "Affected On", "Created On"),
206
                rows);
207
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Price Drop ");
208
        return responseEntity;
209
    }
210
 
31903 amit.gupta 211
    @RequestMapping(value = "/getClosedPricedropItemDescription", method = RequestMethod.GET)
212
    public String getClosedPricedropItemDescription(HttpServletRequest request, Model model) throws Throwable {
213
        List<PriceDrop> priceDrops = priceDropRepository.selectAllComplete();
214
        int processOn = 1;
23819 govind 215
 
31903 amit.gupta 216
        List<PriceDrop> completePriceDrops = priceDrops.stream().filter(x -> x.getCompleteTimestamp() != null)
217
                .collect(Collectors.toList());
23945 amit.gupta 218
 
31903 amit.gupta 219
        Set<Integer> catalogIds = completePriceDrops.stream().map(x -> x.getCatalogItemId())
220
                .collect(Collectors.toSet());
221
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
222
        LOGGER.info("catalogIds" + catalogIds);
23819 govind 223
 
31903 amit.gupta 224
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
225
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
226
        model.addAttribute("priceDrops", completePriceDrops);
227
        model.addAttribute("processOn", processOn);
228
        model.addAttribute("catalogDescription", catalogDescription);
229
        return "price-drop";
230
    }
23945 amit.gupta 231
 
31903 amit.gupta 232
    @RequestMapping(value = "/item-pricing/{itemId}", method = RequestMethod.GET)
233
    public String getItemPricing(HttpServletRequest request, Model model, @PathVariable int itemId) throws Throwable {
23819 govind 234
 
31903 amit.gupta 235
        TagListing tagListing;
236
        PriceDropModel pm = new PriceDropModel();
237
        try {
238
            tagListing = tagListingRepository.selectByItemId(itemId);
239
            if (tagListing != null) {
240
                pm.setMop(tagListing.getMop());
241
                pm.setDp(tagListing.getSellingPrice());
242
                pm.setMrp(tagListing.getMrp());
243
                List<VendorItemPricing> vips = vendorItemPricingRepository.selectAll(itemId);
244
                if (vips.size() > 0) {
245
                    VendorItemPricing vip = vips.get(0);
246
                    pm.setNlc(vip.getNlc());
247
                    pm.setTp(vip.getTp());
248
                } else {
249
                    throw new ProfitMandiBusinessException("Item Id", itemId, "Vendor item pricing does not exist");
250
                }
251
            }
252
        } catch (Exception e) {
253
            LOGGER.info("Chose item that doesn't exist");
254
        }
255
        model.addAttribute("response1", mvcResponseSender.createResponseString(pm));
256
        return "response";
257
    }
27071 amit.gupta 258
 
31903 amit.gupta 259
    @RequestMapping(value = "/item", method = RequestMethod.GET)
260
    public String getItemPricing(HttpServletRequest request, Model model, @RequestParam String query,
261
                                 @RequestParam boolean anyColor) throws Throwable {
262
        String query1 = query.toLowerCase();
24083 amit.gupta 263
 
31903 amit.gupta 264
        List<ItemDescriptionModel> partnersItemDescription = inventoryService
265
                .getAllPartnerItemStringDescription(anyColor).parallelStream()
266
                .filter(x -> x.getItemDescription().toLowerCase().matches(".*?" + query1 + ".*?"))
267
                .collect(Collectors.toList());
268
        LOGGER.info("partnersItemDescription" + partnersItemDescription);
23819 govind 269
 
31903 amit.gupta 270
        model.addAttribute("response1", mvcResponseSender.createResponseString(partnersItemDescription));
271
        return "response";
272
    }
23945 amit.gupta 273
 
31903 amit.gupta 274
    @RequestMapping(value = "/price-drop/imes/download")
275
    public ResponseEntity<ByteArrayResource> downloadPriceDropImeis(HttpServletRequest request,
276
                                                                    @RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws Exception {
277
        Item item = itemRepository.selectById(itemId);
33198 amit.gupta 278
        ByteArrayOutputStream baos = getByteArrayOutputStream(affectedDate, item.getCatalogItemId(), null, Optional.empty());
31903 amit.gupta 279
        final HttpHeaders headers = new HttpHeaders();
280
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
281
        headers.set("Content-disposition", "inline; filename=\"imei-" + item.getItemDescriptionNoColor() + ".csv\"");
282
        byte[] byteArray = baos.toByteArray();
283
        headers.setContentLength(byteArray.length);
284
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
285
    }
23819 govind 286
 
31903 amit.gupta 287
    @RequestMapping(value = "/price-drop/addPayout", method = RequestMethod.POST)
288
    public String updatePriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
289
                                  Model model) throws Exception {
290
        boolean response = false;
291
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
292
        if (priceDrop.getProcessTimestamp() == null) {
293
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
294
            priceDrop.setPriceDropIn(priceDropProcessModel.getPriceDropIn());
295
            // priceDrop.setProcessTimestamp(LocalDateTime.now());
296
            priceDropRepository.persist(priceDrop);
297
            response = true;
298
        }
299
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
300
        return "response";
301
    }
24083 amit.gupta 302
 
31903 amit.gupta 303
    @RequestMapping(value = "/priceDropImeis/{priceDropId}", method = RequestMethod.GET)
304
    public String priceDropStatus(HttpServletRequest request, @PathVariable int priceDropId, Model model)
305
            throws Exception {
29951 amit.gupta 306
 
31903 amit.gupta 307
        PriceDropImeisModel priceDropImeisModel = new PriceDropImeisModel();
23819 govind 308
 
31903 amit.gupta 309
        // This call is used to persit imeis to pricedrop imeis in case its not there.
310
        // This should be called while creating price drop.
311
        // priceDropService.priceDropStatus(priceDropId);
24083 amit.gupta 312
 
31903 amit.gupta 313
        List<String> pendingImeis = new ArrayList<>();
314
        List<String> approvedImeis = new ArrayList<>();
315
        List<String> rejectedImeis = new ArrayList<>();
316
        List<String> holdImeis = new ArrayList<>();
317
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
318
        for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
319
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.PENDING)) {
320
                pendingImeis.add(priceDropIMEI.getImei());
321
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)) {
322
                approvedImeis.add(priceDropIMEI.getImei());
323
            }
324
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.REJECTED)) {
325
                rejectedImeis.add(priceDropIMEI.getImei());
326
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
327
                holdImeis.add(priceDropIMEI.getImei());
24083 amit.gupta 328
 
31903 amit.gupta 329
            }
330
        }
331
        LOGGER.info("pendingImeis" + pendingImeis);
332
        LOGGER.info("approvedImeis" + approvedImeis);
333
        LOGGER.info("rejectedImeis" + rejectedImeis);
334
        LOGGER.info("priceDropImeis" + priceDropImeis);
23945 amit.gupta 335
 
31903 amit.gupta 336
        priceDropImeisModel.setPendingImeis(pendingImeis);
337
        priceDropImeisModel.setPriceDropId(priceDropId);
338
        priceDropImeisModel.setApprovedImeis(approvedImeis);
339
        priceDropImeisModel.setHoldImeis(holdImeis);
340
        priceDropImeisModel.setRejectedImeis(rejectedImeis);
341
        model.addAttribute("response1", mvcResponseSender.createResponseString(priceDropImeisModel));
342
        return "response";
343
    }
28102 tejbeer 344
 
31903 amit.gupta 345
    @RequestMapping(value = "/processPriceDrop", method = RequestMethod.POST)
346
    public String processPriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
347
                                   Model model) throws Exception {
348
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
349
        boolean response = false;
350
        if (priceDrop.getPartnerPayout() == 0) {
351
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
352
        }
353
        priceDrop.setProcessTimestamp(LocalDateTime.now());
354
        priceDropService.processPriceDrop(priceDrop.getId(), priceDropProcessModel.isActivatedOnly());
355
        response = true;
356
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
357
        return "response";
358
    }
28102 tejbeer 359
 
37000 amit 360
    // On-demand price-hike deduction for a whole hike: figures out billed partners/IMEIs, then
361
    // debits each partner in the background (one transaction per retailer). Idempotent — re-calling
362
    // skips units already recovered (incl. those already handled by the GRN hook).
363
    @RequestMapping(value = "/priceHike/process/{priceDropId}", method = RequestMethod.GET)
364
    public String processPriceHike(HttpServletRequest request, @PathVariable int priceDropId, Model model)
36983 amit 365
            throws Exception {
37000 amit 366
        priceHikeService.triggerHikeDeduction(priceDropId);
367
        model.addAttribute("response1",
368
                mvcResponseSender.createResponseString("Price hike deduction started for priceDropId " + priceDropId));
36983 amit 369
        return "response";
370
    }
371
 
31903 amit.gupta 372
    @RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
373
    public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
374
            throws Exception {
375
        boolean response = false;
376
        priceDropModel.setAllColors(true);
377
        if (this.validatePriceDrop(priceDropModel)) {
378
            TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
379
            float oldDp = tagListing.getSellingPrice();
380
            float oldMop = tagListing.getMop();
381
            float oldTp = 0;
382
            float newDp = priceDropModel.getDp();
28102 tejbeer 383
 
31903 amit.gupta 384
            if (newDp != oldDp) {
385
                List<Item> allItems = null;
386
                Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
387
                if (priceDropModel.isAllColors()) {
388
                    allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
28102 tejbeer 389
 
31903 amit.gupta 390
                } else {
391
                    allItems = Arrays.asList(currentItem);
392
                }
393
                for (Item item : allItems) {
394
                    TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
395
                    if (itemTagListing == null)
396
                        continue;
397
                    itemTagListing.setSellingPrice(newDp);
398
                    itemTagListing.setMop(priceDropModel.getMop());
399
                    List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
400
                    for (VendorItemPricing vip : vipList) {
401
                        oldTp = vip.getNlc();
402
                        vip.setDp(newDp);
403
                        vip.setMop(priceDropModel.getMop());
404
                        //Lets not update NLC/TP as it has to be managed by Category Tea,
405
                        //vip.setNlc(priceDropModel.getTp());
406
                        //vip.setTp(priceDropModel.getTp());
407
                        vendorItemPricingRepository.persist(vip);
408
                    }
409
                    transactionService.updatePriceDrop(item.getId(), newDp);
410
                }
29926 amit.gupta 411
 
31903 amit.gupta 412
                // Add to itemPricing history
413
                ItemPricingHistory iph = new ItemPricingHistory();
414
                iph.setCatalogId(currentItem.getCatalogItemId());
415
                iph.setTp(priceDropModel.getTp());
416
                iph.setDp(priceDropModel.getDp());
417
                iph.setMop(priceDropModel.getMop());
418
                // TODO: changedBy
419
                iph.setChangedBy("me");
420
                iph.setCreateTimestamp(LocalDateTime.now());
421
                itemPricingHistoryRepository.persist(iph);
28136 tejbeer 422
 
31903 amit.gupta 423
                PriceDrop priceDrop = new PriceDrop();
424
                priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
425
                priceDrop.setTp(oldTp);
426
                priceDrop.setNlc(oldTp);
427
                priceDrop.setMop(oldMop);
428
                priceDrop.setOldDp(oldDp);
429
                priceDrop.setAmount(oldDp - newDp);
430
                priceDrop.setNewDp(newDp);
431
                priceDrop.setCreatedOn(LocalDateTime.now());
432
                priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
433
                priceDropRepository.persist(priceDrop);
434
                priceDropService.priceDropStatus(priceDrop.getId());
435
                response = true;
30471 amit.gupta 436
 
31903 amit.gupta 437
                this.sendPriceChangeNotification(priceDrop);
35547 amit 438
 
439
                // Publish event for real-time Solr update
440
                try {
441
                    tagListingEventPublisher.publishPriceChange(0, currentItem.getCatalogItemId());
442
                } catch (Exception e) {
443
                    LOGGER.error("Failed to publish price change event for catalogId: {}", currentItem.getCatalogItemId(), e);
444
                }
31903 amit.gupta 445
            } else {
446
                throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
447
                        "Price Drop Should be greater than 0");
448
            }
449
        }
450
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
451
        return "response";
452
    }
29654 tejbeer 453
 
31903 amit.gupta 454
    private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
455
        List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
456
        String title = "Price has been %s for %s";
24083 amit.gupta 457
 
28568 amit.gupta 458
 
31903 amit.gupta 459
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
460
        sendNotificationModel.setCampaignName("pricechange");
461
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
462
        sendNotificationModel.setTitle("");
463
        StringBuffer sb = new StringBuffer();
464
        String message = null;
465
        if (priceDrop.getDropAmount() > 0) {
466
            title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
467
            message = String.format("Price has been dropped from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(priceDrop.getDropAmount()),
468
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
469
        } else {
470
            title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
471
            message = String.format("Price has been increased from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(-priceDrop.getDropAmount()),
472
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
473
        }
474
        sendNotificationModel.setTitle(title);
475
        sendNotificationModel.setMessage(message);
476
        sendNotificationModel.setMessageType(MessageType.pricechange);
477
        notificationService.sendNotificationToAll(sendNotificationModel);
478
    }
28568 amit.gupta 479
 
31903 amit.gupta 480
    @RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
481
    public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
482
                                                        Model model) throws ProfitMandiBusinessException, Exception {
28568 amit.gupta 483
 
31903 amit.gupta 484
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
485
        Map<String, PriceDropIMEI> priceDropIMEIsMap = priceDropIMEIRepository.selectByPriceDropId(priceDropId).stream()
486
                .collect(Collectors.toMap(x -> x.getImei(), x -> x));
487
        LOGGER.info("PriceDropImeis {}, priceDropId {}", priceDropIMEIsMap, priceDropId);
488
        Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
489
        final HttpHeaders headers = new HttpHeaders();
490
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
491
        headers.set("Content-disposition",
492
                "inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
493
                        + FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
494
        ByteArrayOutputStream baos = null;
495
        if (priceDropIMEIsMap.size() == 0) {
496
            priceDropService.priceDropStatus(priceDrop.getId());
497
            baos = FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
498
                    "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
499
                    "Grn On", "Activation Timestamp", "Activation Added On"), new ArrayList<>());
500
        } else {
28568 amit.gupta 501
 
31903 amit.gupta 502
            LOGGER.info("In else block");
33198 amit.gupta 503
            baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(), priceDropIMEIsMap, Optional.of(priceDrop.getCreatedOn()));
31903 amit.gupta 504
        }
505
        byte[] byteArray = baos.toByteArray();
506
        headers.setContentLength(byteArray.length);
507
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
24083 amit.gupta 508
 
31903 amit.gupta 509
    }
24083 amit.gupta 510
 
31903 amit.gupta 511
    @RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
33470 amit.gupta 512
    public String updatePriceDropImeis(@RequestBody PriceDropImeisModel priceDropImeisModel,
513
                                       Model model) throws Exception {
32012 amit.gupta 514
        final PriceDropImeiStatus status;
28102 tejbeer 515
 
31903 amit.gupta 516
        switch (priceDropImeisModel.getUpdatedStatus()) {
517
            case "approved": {
518
                status = PriceDropImeiStatus.APPROVED;
519
                break;
520
            }
32012 amit.gupta 521
            case "pending": {
522
                status = PriceDropImeiStatus.PENDING;
31903 amit.gupta 523
                break;
524
            }
525
            case "rejected": {
526
                status = PriceDropImeiStatus.REJECTED;
527
                break;
528
            }
32012 amit.gupta 529
            case "hold": {
530
                status = PriceDropImeiStatus.HOLD;
531
                break;
532
            }
533
            default:
534
                throw new IllegalStateException("Unexpected value: " + priceDropImeisModel.getUpdatedStatus());
31903 amit.gupta 535
        }
24168 amit.gupta 536
 
31903 amit.gupta 537
        if (PriceDropImeiStatus.PENDING.equals(status)) {
32012 amit.gupta 538
            List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByStatuses(Arrays.asList(PriceDropImeiStatus.REJECTED, PriceDropImeiStatus.HOLD),
31903 amit.gupta 539
                    priceDropImeisModel.getPriceDropId());
540
            LOGGER.info("hello" + priceDropIMEIs);
32012 amit.gupta 541
            for (PriceDropIMEI priceDropIMEI : priceDropIMEIs) {
542
                if (priceDropIMEI.getStatus().equals(status) || !priceDropImeisModel.getUpdatedImeis().contains(priceDropIMEI.getImei())) {
543
                    continue;
31903 amit.gupta 544
                }
32012 amit.gupta 545
                priceDropIMEI.setStatus(PriceDropImeiStatus.PENDING);
31903 amit.gupta 546
            }
547
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
548
            return "response";
549
        }
23951 amit.gupta 550
 
32012 amit.gupta 551
        if (status.equals(PriceDropImeiStatus.APPROVED)) {
552
            priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
553
                    priceDropImeisModel.getUpdatedImeis());
554
        }
555
 
31903 amit.gupta 556
        List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
557
                .selectByPriceDropId(priceDropImeisModel.getPriceDropId());
558
        List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
559
                .filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
32012 amit.gupta 560
                .filter(x -> !x.getStatus().equals(status)).collect(Collectors.toList());
31903 amit.gupta 561
        for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
562
            if (status.equals(PriceDropImeiStatus.REJECTED)
563
                    && priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
564
                priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
565
                priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
566
                priceDropImei.setRejectTimestamp(LocalDateTime.now());
567
            } else if (status.equals(PriceDropImeiStatus.HOLD)) {
568
                if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
569
                    priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
570
                } else {
571
                    throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
572
                }
28568 amit.gupta 573
 
31903 amit.gupta 574
            }
28568 amit.gupta 575
 
31903 amit.gupta 576
        }
28568 amit.gupta 577
 
31903 amit.gupta 578
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
579
        return "response";
24083 amit.gupta 580
 
31903 amit.gupta 581
    }
24083 amit.gupta 582
 
31903 amit.gupta 583
    private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
33198 amit.gupta 584
                                                           Map<String, PriceDropIMEI> priceDropImeis, Optional<LocalDateTime> createdOn) throws Exception {
585
 
31903 amit.gupta 586
        List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
33198 amit.gupta 587
                .getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId, createdOn);
31903 amit.gupta 588
        List<List<?>> rows = new ArrayList<>();
589
        for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
590
            if (priceDropImeis == null) {
591
                rows.add(this.getRow(imeiDropSummaryModel, null));
592
            } else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
593
                rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
594
            }
595
        }
596
        return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
597
                "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
598
                "Grn On", "Activation Timestamp", "Activation Added On"), rows);
599
    }
24083 amit.gupta 600
 
31903 amit.gupta 601
    private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
602
                                                PriceDropIMEI priceDropIMEI) {
603
        List<Serializable> row = new ArrayList<>();
604
        row.add(imeiDropSummaryModel.getSerialNumber());
605
        row.add(imeiDropSummaryModel.getStoreName());
606
        row.add(imeiDropSummaryModel.getPartnerCode());
607
        row.add(imeiDropSummaryModel.getItemId());
608
        row.add(imeiDropSummaryModel.getBrand());
609
        row.add(imeiDropSummaryModel.getModelName());
610
        row.add(imeiDropSummaryModel.getModelNumber());
611
        row.add(imeiDropSummaryModel.getColor());
612
        if (priceDropIMEI != null) {
613
            row.add(priceDropIMEI.getStatus());
614
            row.add(priceDropIMEI.getRejectionReason());
615
        } else {
616
            row.add(PriceDropImeiStatus.PENDING);
617
            row.add("");
618
        }
619
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
620
        row.add(imeiDropSummaryModel.getVendorName());
621
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
622
        row.add(imeiDropSummaryModel.getActivationTimestamp());
623
        row.add(imeiDropSummaryModel.getActivationAddedOn());
624
        return row;
625
    }
23819 govind 626
 
31903 amit.gupta 627
    private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
628
        if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
629
            return true;
630
        }
631
        return false;
632
    }
23945 amit.gupta 633
 
32844 shampa 634
    @Autowired
635
    BrandsService brandsService;
33470 amit.gupta 636
 
31903 amit.gupta 637
    @RequestMapping(value = "/priceCircular")
638
    public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
639
        int fofoId = Utils.SYSTEM_PARTNER_ID;
32844 shampa 640
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
31903 amit.gupta 641
        model.addAttribute("brands", brands);
642
        model.addAttribute("isAdmin", true);
643
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 644
 
31903 amit.gupta 645
        return "partner-price-circular";
646
    }
28102 tejbeer 647
 
31903 amit.gupta 648
    @RequestMapping(value = "/partnerPriceCircular")
649
    public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
650
        int fofoId = Utils.SYSTEM_PARTNER_ID;
32844 shampa 651
        Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
652
        brands.addAll(brandsService.getBrandsToDisplay(6).stream().map(x -> (String) x.getName())
31903 amit.gupta 653
                .collect(Collectors.toSet()));
654
        model.addAttribute("brands", brands);
655
        model.addAttribute("isAdmin", false);
28102 tejbeer 656
 
31903 amit.gupta 657
        return "partner-price-circular";
658
    }
28102 tejbeer 659
 
31903 amit.gupta 660
    @RequestMapping(value = "/priceCircularByBrand")
661
    public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
662
            throws ProfitMandiBusinessException {
663
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
664
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
665
        } else {
666
            fofoId = loginDetails.getFofoId();
667
        }
32905 shampa 668
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
669
 
31903 amit.gupta 670
        //.minusDays(2)
34317 amit.gupta 671
        PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
35395 amit 672
        //Get slowmong/missign category for that brand
673
        //get stock with us missing as well as with partner missing
674
        //filter that stock
34317 amit.gupta 675
        return this.getPriceCircularView(priceCircularModel, model, fs.getCode());
32331 amit.gupta 676
    }
677
 
34317 amit.gupta 678
    public String getPriceCircularView(PriceCircularModel priceCircularModel, Model model, String partnerCode) {
679
        List<String> allMarginsSet = new ArrayList<>(this.getSchemeHeaders(priceCircularModel));
680
        List<String> sellins = SchemeType.IN_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
681
        List<String> sellouts = SchemeType.OUT_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
682
        List<String> allMargins = new ArrayList<>();
683
        allMargins.addAll(sellins);
684
        allMargins.addAll(sellouts);
31903 amit.gupta 685
        LOGGER.info("Sellins - {}", sellins);
686
        LOGGER.info("Sellouts - {}", sellouts);
34317 amit.gupta 687
        model.addAttribute("priceCircularItemModels", priceCircularModel.getPriceCircularItemModelNews());
31903 amit.gupta 688
        model.addAttribute("allMargins", allMargins);
689
        model.addAttribute("sellins", sellins);
690
        model.addAttribute("sellouts", sellouts);
34317 amit.gupta 691
        model.addAttribute("offers", priceCircularModel.getOffers());
692
        model.addAttribute("upgradeOffer", priceCircularModel.isUpgradeOffer());
31903 amit.gupta 693
        model.addAttribute("mvcResponseSender", mvcResponseSender);
32905 shampa 694
        model.addAttribute("partnerCode", partnerCode);
32331 amit.gupta 695
        return "price-circular-table";
31903 amit.gupta 696
    }
29951 amit.gupta 697
 
31903 amit.gupta 698
    private Set<String> getSchemeHeaders(PriceCircularModel priceCircular) {
699
        Set<String> schemeHeaders = new HashSet<>();
700
        priceCircular.getPriceCircularItemModelNews().stream().forEach(priceCircularItemModelNew -> {
701
            Map<String, AmountModel> headerMap = new HashMap<>();
702
            priceCircularItemModelNew.setHeaderSchemeModelsMap(headerMap);
703
            priceCircularItemModelNew.getSchemeSummaryModels().stream().forEach(schemeSummaryModel -> {
704
                if (schemeSummaryModel == null) return;
34317 amit.gupta 705
                schemeSummaryModel.setHeader(schemeSummaryModel.getSchemeType().getValue());
31903 amit.gupta 706
                if (!headerMap.containsKey(schemeSummaryModel.getHeader())) {
707
                    headerMap.put(schemeSummaryModel.getHeader(), new AmountModel(schemeSummaryModel.getAmount(), schemeSummaryModel.getAmountType()));
708
                } else {
709
                    AmountModel model = headerMap.get(schemeSummaryModel.getHeader());
710
                    model.setAmount(model.getAmount() + schemeSummaryModel.getAmount());
711
                }
712
                schemeHeaders.add(schemeSummaryModel.getHeader());
713
            });
714
        });
28102 tejbeer 715
 
31903 amit.gupta 716
        LOGGER.info("Scheme headers - {}", schemeHeaders);
717
        return schemeHeaders;
718
    }
30250 amit.gupta 719
 
31903 amit.gupta 720
    //private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
721
    //private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
30471 amit.gupta 722
 
30562 amit.gupta 723
 
31903 amit.gupta 724
    @RequestMapping(value = "/downloadNlcByBrand")
725
    public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
726
                                                                @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
727
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
728
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
729
        } else {
730
            fofoId = loginDetails.getFofoId();
731
        }
732
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
733
        /*List<Integer> catalogIds = priceCircular.getPriceCircularItemModelNews().stream().limit(10).map(x->x.getCatalogId()).collect(Collectors.toList());
734
        priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());*/
735
        ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
736
        final HttpHeaders headers = new HttpHeaders();
737
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
738
        headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
739
        byte[] byteArray = baos.toByteArray();
740
        headers.setContentLength(byteArray.length);
741
        return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
742
    }
30471 amit.gupta 743
 
31903 amit.gupta 744
    private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
745
        List<List<?>> rows = new ArrayList<>();
746
        for (PriceCircularItemModelNew priceCircularItemModel : priceCircular.getPriceCircularItemModelNews()) {
747
            List<Serializable> row = new ArrayList<>();
748
            row.add(priceCircularItemModel.getCatalogId());
749
            row.add(brand);
750
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelName());
751
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelNumber());
752
            //TODO: fix nlc
753
            //row.add(priceCircularItemModel.getNetPrice());
754
            rows.add(row);
755
        }
756
        return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
757
    }
30471 amit.gupta 758
 
31903 amit.gupta 759
    @RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
760
    public String selectPriceDropStatus(HttpServletRequest request,
761
                                        @RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
762
                                        Model model) throws Exception {
30250 amit.gupta 763
 
31903 amit.gupta 764
        model.addAttribute("selectedStatus", selectedStatus);
765
        return "pricedrop-status-change";
766
    }
30250 amit.gupta 767
 
23819 govind 768
}