Subversion Repositories SmartDukaan

Rev

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