Subversion Repositories SmartDukaan

Rev

Rev 35395 | 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());
351
        priceDropService.processPriceDrop(priceDrop.getId(), priceDropProcessModel.isActivatedOnly());
352
        response = true;
353
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
354
        return "response";
355
    }
28102 tejbeer 356
 
31903 amit.gupta 357
    @RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
358
    public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
359
            throws Exception {
360
        boolean response = false;
361
        priceDropModel.setAllColors(true);
362
        if (this.validatePriceDrop(priceDropModel)) {
363
            TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
364
            float oldDp = tagListing.getSellingPrice();
365
            float oldMop = tagListing.getMop();
366
            float oldTp = 0;
367
            float newDp = priceDropModel.getDp();
28102 tejbeer 368
 
31903 amit.gupta 369
            if (newDp != oldDp) {
370
                List<Item> allItems = null;
371
                Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
372
                if (priceDropModel.isAllColors()) {
373
                    allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
28102 tejbeer 374
 
31903 amit.gupta 375
                } else {
376
                    allItems = Arrays.asList(currentItem);
377
                }
378
                for (Item item : allItems) {
379
                    TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
380
                    if (itemTagListing == null)
381
                        continue;
382
                    itemTagListing.setSellingPrice(newDp);
383
                    itemTagListing.setMop(priceDropModel.getMop());
384
                    List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
385
                    for (VendorItemPricing vip : vipList) {
386
                        oldTp = vip.getNlc();
387
                        vip.setDp(newDp);
388
                        vip.setMop(priceDropModel.getMop());
389
                        //Lets not update NLC/TP as it has to be managed by Category Tea,
390
                        //vip.setNlc(priceDropModel.getTp());
391
                        //vip.setTp(priceDropModel.getTp());
392
                        vendorItemPricingRepository.persist(vip);
393
                    }
394
                    transactionService.updatePriceDrop(item.getId(), newDp);
395
                }
29926 amit.gupta 396
 
31903 amit.gupta 397
                // Add to itemPricing history
398
                ItemPricingHistory iph = new ItemPricingHistory();
399
                iph.setCatalogId(currentItem.getCatalogItemId());
400
                iph.setTp(priceDropModel.getTp());
401
                iph.setDp(priceDropModel.getDp());
402
                iph.setMop(priceDropModel.getMop());
403
                // TODO: changedBy
404
                iph.setChangedBy("me");
405
                iph.setCreateTimestamp(LocalDateTime.now());
406
                itemPricingHistoryRepository.persist(iph);
28136 tejbeer 407
 
31903 amit.gupta 408
                PriceDrop priceDrop = new PriceDrop();
409
                priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
410
                priceDrop.setTp(oldTp);
411
                priceDrop.setNlc(oldTp);
412
                priceDrop.setMop(oldMop);
413
                priceDrop.setOldDp(oldDp);
414
                priceDrop.setAmount(oldDp - newDp);
415
                priceDrop.setNewDp(newDp);
416
                priceDrop.setCreatedOn(LocalDateTime.now());
417
                priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
418
                priceDropRepository.persist(priceDrop);
419
                priceDropService.priceDropStatus(priceDrop.getId());
420
                response = true;
30471 amit.gupta 421
 
31903 amit.gupta 422
                this.sendPriceChangeNotification(priceDrop);
35547 amit 423
 
424
                // Publish event for real-time Solr update
425
                try {
426
                    tagListingEventPublisher.publishPriceChange(0, currentItem.getCatalogItemId());
427
                } catch (Exception e) {
428
                    LOGGER.error("Failed to publish price change event for catalogId: {}", currentItem.getCatalogItemId(), e);
429
                }
31903 amit.gupta 430
            } else {
431
                throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
432
                        "Price Drop Should be greater than 0");
433
            }
434
        }
435
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
436
        return "response";
437
    }
29654 tejbeer 438
 
31903 amit.gupta 439
    private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
440
        List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
441
        String title = "Price has been %s for %s";
24083 amit.gupta 442
 
28568 amit.gupta 443
 
31903 amit.gupta 444
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
445
        sendNotificationModel.setCampaignName("pricechange");
446
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
447
        sendNotificationModel.setTitle("");
448
        StringBuffer sb = new StringBuffer();
449
        String message = null;
450
        if (priceDrop.getDropAmount() > 0) {
451
            title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
452
            message = String.format("Price has been dropped from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(priceDrop.getDropAmount()),
453
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
454
        } else {
455
            title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
456
            message = String.format("Price has been increased from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(-priceDrop.getDropAmount()),
457
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
458
        }
459
        sendNotificationModel.setTitle(title);
460
        sendNotificationModel.setMessage(message);
461
        sendNotificationModel.setMessageType(MessageType.pricechange);
462
        notificationService.sendNotificationToAll(sendNotificationModel);
463
    }
28568 amit.gupta 464
 
31903 amit.gupta 465
    @RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
466
    public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
467
                                                        Model model) throws ProfitMandiBusinessException, Exception {
28568 amit.gupta 468
 
31903 amit.gupta 469
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
470
        Map<String, PriceDropIMEI> priceDropIMEIsMap = priceDropIMEIRepository.selectByPriceDropId(priceDropId).stream()
471
                .collect(Collectors.toMap(x -> x.getImei(), x -> x));
472
        LOGGER.info("PriceDropImeis {}, priceDropId {}", priceDropIMEIsMap, priceDropId);
473
        Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
474
        final HttpHeaders headers = new HttpHeaders();
475
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
476
        headers.set("Content-disposition",
477
                "inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
478
                        + FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
479
        ByteArrayOutputStream baos = null;
480
        if (priceDropIMEIsMap.size() == 0) {
481
            priceDropService.priceDropStatus(priceDrop.getId());
482
            baos = FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
483
                    "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
484
                    "Grn On", "Activation Timestamp", "Activation Added On"), new ArrayList<>());
485
        } else {
28568 amit.gupta 486
 
31903 amit.gupta 487
            LOGGER.info("In else block");
33198 amit.gupta 488
            baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(), priceDropIMEIsMap, Optional.of(priceDrop.getCreatedOn()));
31903 amit.gupta 489
        }
490
        byte[] byteArray = baos.toByteArray();
491
        headers.setContentLength(byteArray.length);
492
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
24083 amit.gupta 493
 
31903 amit.gupta 494
    }
24083 amit.gupta 495
 
31903 amit.gupta 496
    @RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
33470 amit.gupta 497
    public String updatePriceDropImeis(@RequestBody PriceDropImeisModel priceDropImeisModel,
498
                                       Model model) throws Exception {
32012 amit.gupta 499
        final PriceDropImeiStatus status;
28102 tejbeer 500
 
31903 amit.gupta 501
        switch (priceDropImeisModel.getUpdatedStatus()) {
502
            case "approved": {
503
                status = PriceDropImeiStatus.APPROVED;
504
                break;
505
            }
32012 amit.gupta 506
            case "pending": {
507
                status = PriceDropImeiStatus.PENDING;
31903 amit.gupta 508
                break;
509
            }
510
            case "rejected": {
511
                status = PriceDropImeiStatus.REJECTED;
512
                break;
513
            }
32012 amit.gupta 514
            case "hold": {
515
                status = PriceDropImeiStatus.HOLD;
516
                break;
517
            }
518
            default:
519
                throw new IllegalStateException("Unexpected value: " + priceDropImeisModel.getUpdatedStatus());
31903 amit.gupta 520
        }
24168 amit.gupta 521
 
31903 amit.gupta 522
        if (PriceDropImeiStatus.PENDING.equals(status)) {
32012 amit.gupta 523
            List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByStatuses(Arrays.asList(PriceDropImeiStatus.REJECTED, PriceDropImeiStatus.HOLD),
31903 amit.gupta 524
                    priceDropImeisModel.getPriceDropId());
525
            LOGGER.info("hello" + priceDropIMEIs);
32012 amit.gupta 526
            for (PriceDropIMEI priceDropIMEI : priceDropIMEIs) {
527
                if (priceDropIMEI.getStatus().equals(status) || !priceDropImeisModel.getUpdatedImeis().contains(priceDropIMEI.getImei())) {
528
                    continue;
31903 amit.gupta 529
                }
32012 amit.gupta 530
                priceDropIMEI.setStatus(PriceDropImeiStatus.PENDING);
31903 amit.gupta 531
            }
532
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
533
            return "response";
534
        }
23951 amit.gupta 535
 
32012 amit.gupta 536
        if (status.equals(PriceDropImeiStatus.APPROVED)) {
537
            priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
538
                    priceDropImeisModel.getUpdatedImeis());
539
        }
540
 
31903 amit.gupta 541
        List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
542
                .selectByPriceDropId(priceDropImeisModel.getPriceDropId());
543
        List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
544
                .filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
32012 amit.gupta 545
                .filter(x -> !x.getStatus().equals(status)).collect(Collectors.toList());
31903 amit.gupta 546
        for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
547
            if (status.equals(PriceDropImeiStatus.REJECTED)
548
                    && priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
549
                priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
550
                priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
551
                priceDropImei.setRejectTimestamp(LocalDateTime.now());
552
            } else if (status.equals(PriceDropImeiStatus.HOLD)) {
553
                if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
554
                    priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
555
                } else {
556
                    throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
557
                }
28568 amit.gupta 558
 
31903 amit.gupta 559
            }
28568 amit.gupta 560
 
31903 amit.gupta 561
        }
28568 amit.gupta 562
 
31903 amit.gupta 563
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
564
        return "response";
24083 amit.gupta 565
 
31903 amit.gupta 566
    }
24083 amit.gupta 567
 
31903 amit.gupta 568
    private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
33198 amit.gupta 569
                                                           Map<String, PriceDropIMEI> priceDropImeis, Optional<LocalDateTime> createdOn) throws Exception {
570
 
31903 amit.gupta 571
        List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
33198 amit.gupta 572
                .getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId, createdOn);
31903 amit.gupta 573
        List<List<?>> rows = new ArrayList<>();
574
        for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
575
            if (priceDropImeis == null) {
576
                rows.add(this.getRow(imeiDropSummaryModel, null));
577
            } else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
578
                rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
579
            }
580
        }
581
        return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
582
                "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
583
                "Grn On", "Activation Timestamp", "Activation Added On"), rows);
584
    }
24083 amit.gupta 585
 
31903 amit.gupta 586
    private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
587
                                                PriceDropIMEI priceDropIMEI) {
588
        List<Serializable> row = new ArrayList<>();
589
        row.add(imeiDropSummaryModel.getSerialNumber());
590
        row.add(imeiDropSummaryModel.getStoreName());
591
        row.add(imeiDropSummaryModel.getPartnerCode());
592
        row.add(imeiDropSummaryModel.getItemId());
593
        row.add(imeiDropSummaryModel.getBrand());
594
        row.add(imeiDropSummaryModel.getModelName());
595
        row.add(imeiDropSummaryModel.getModelNumber());
596
        row.add(imeiDropSummaryModel.getColor());
597
        if (priceDropIMEI != null) {
598
            row.add(priceDropIMEI.getStatus());
599
            row.add(priceDropIMEI.getRejectionReason());
600
        } else {
601
            row.add(PriceDropImeiStatus.PENDING);
602
            row.add("");
603
        }
604
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
605
        row.add(imeiDropSummaryModel.getVendorName());
606
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
607
        row.add(imeiDropSummaryModel.getActivationTimestamp());
608
        row.add(imeiDropSummaryModel.getActivationAddedOn());
609
        return row;
610
    }
23819 govind 611
 
31903 amit.gupta 612
    private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
613
        if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
614
            return true;
615
        }
616
        return false;
617
    }
23945 amit.gupta 618
 
32844 shampa 619
    @Autowired
620
    BrandsService brandsService;
33470 amit.gupta 621
 
31903 amit.gupta 622
    @RequestMapping(value = "/priceCircular")
623
    public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
624
        int fofoId = Utils.SYSTEM_PARTNER_ID;
32844 shampa 625
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
31903 amit.gupta 626
        model.addAttribute("brands", brands);
627
        model.addAttribute("isAdmin", true);
628
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 629
 
31903 amit.gupta 630
        return "partner-price-circular";
631
    }
28102 tejbeer 632
 
31903 amit.gupta 633
    @RequestMapping(value = "/partnerPriceCircular")
634
    public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
635
        int fofoId = Utils.SYSTEM_PARTNER_ID;
32844 shampa 636
        Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
637
        brands.addAll(brandsService.getBrandsToDisplay(6).stream().map(x -> (String) x.getName())
31903 amit.gupta 638
                .collect(Collectors.toSet()));
639
        model.addAttribute("brands", brands);
640
        model.addAttribute("isAdmin", false);
28102 tejbeer 641
 
31903 amit.gupta 642
        return "partner-price-circular";
643
    }
28102 tejbeer 644
 
31903 amit.gupta 645
    @RequestMapping(value = "/priceCircularByBrand")
646
    public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
647
            throws ProfitMandiBusinessException {
648
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
649
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
650
        } else {
651
            fofoId = loginDetails.getFofoId();
652
        }
32905 shampa 653
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
654
 
31903 amit.gupta 655
        //.minusDays(2)
34317 amit.gupta 656
        PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
35395 amit 657
        //Get slowmong/missign category for that brand
658
        //get stock with us missing as well as with partner missing
659
        //filter that stock
34317 amit.gupta 660
        return this.getPriceCircularView(priceCircularModel, model, fs.getCode());
32331 amit.gupta 661
    }
662
 
34317 amit.gupta 663
    public String getPriceCircularView(PriceCircularModel priceCircularModel, Model model, String partnerCode) {
664
        List<String> allMarginsSet = new ArrayList<>(this.getSchemeHeaders(priceCircularModel));
665
        List<String> sellins = SchemeType.IN_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
666
        List<String> sellouts = SchemeType.OUT_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
667
        List<String> allMargins = new ArrayList<>();
668
        allMargins.addAll(sellins);
669
        allMargins.addAll(sellouts);
31903 amit.gupta 670
        LOGGER.info("Sellins - {}", sellins);
671
        LOGGER.info("Sellouts - {}", sellouts);
34317 amit.gupta 672
        model.addAttribute("priceCircularItemModels", priceCircularModel.getPriceCircularItemModelNews());
31903 amit.gupta 673
        model.addAttribute("allMargins", allMargins);
674
        model.addAttribute("sellins", sellins);
675
        model.addAttribute("sellouts", sellouts);
34317 amit.gupta 676
        model.addAttribute("offers", priceCircularModel.getOffers());
677
        model.addAttribute("upgradeOffer", priceCircularModel.isUpgradeOffer());
31903 amit.gupta 678
        model.addAttribute("mvcResponseSender", mvcResponseSender);
32905 shampa 679
        model.addAttribute("partnerCode", partnerCode);
32331 amit.gupta 680
        return "price-circular-table";
31903 amit.gupta 681
    }
29951 amit.gupta 682
 
31903 amit.gupta 683
    private Set<String> getSchemeHeaders(PriceCircularModel priceCircular) {
684
        Set<String> schemeHeaders = new HashSet<>();
685
        priceCircular.getPriceCircularItemModelNews().stream().forEach(priceCircularItemModelNew -> {
686
            Map<String, AmountModel> headerMap = new HashMap<>();
687
            priceCircularItemModelNew.setHeaderSchemeModelsMap(headerMap);
688
            priceCircularItemModelNew.getSchemeSummaryModels().stream().forEach(schemeSummaryModel -> {
689
                if (schemeSummaryModel == null) return;
34317 amit.gupta 690
                schemeSummaryModel.setHeader(schemeSummaryModel.getSchemeType().getValue());
31903 amit.gupta 691
                if (!headerMap.containsKey(schemeSummaryModel.getHeader())) {
692
                    headerMap.put(schemeSummaryModel.getHeader(), new AmountModel(schemeSummaryModel.getAmount(), schemeSummaryModel.getAmountType()));
693
                } else {
694
                    AmountModel model = headerMap.get(schemeSummaryModel.getHeader());
695
                    model.setAmount(model.getAmount() + schemeSummaryModel.getAmount());
696
                }
697
                schemeHeaders.add(schemeSummaryModel.getHeader());
698
            });
699
        });
28102 tejbeer 700
 
31903 amit.gupta 701
        LOGGER.info("Scheme headers - {}", schemeHeaders);
702
        return schemeHeaders;
703
    }
30250 amit.gupta 704
 
31903 amit.gupta 705
    //private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
706
    //private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
30471 amit.gupta 707
 
30562 amit.gupta 708
 
31903 amit.gupta 709
    @RequestMapping(value = "/downloadNlcByBrand")
710
    public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
711
                                                                @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
712
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
713
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
714
        } else {
715
            fofoId = loginDetails.getFofoId();
716
        }
717
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
718
        /*List<Integer> catalogIds = priceCircular.getPriceCircularItemModelNews().stream().limit(10).map(x->x.getCatalogId()).collect(Collectors.toList());
719
        priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());*/
720
        ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
721
        final HttpHeaders headers = new HttpHeaders();
722
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
723
        headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
724
        byte[] byteArray = baos.toByteArray();
725
        headers.setContentLength(byteArray.length);
726
        return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
727
    }
30471 amit.gupta 728
 
31903 amit.gupta 729
    private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
730
        List<List<?>> rows = new ArrayList<>();
731
        for (PriceCircularItemModelNew priceCircularItemModel : priceCircular.getPriceCircularItemModelNews()) {
732
            List<Serializable> row = new ArrayList<>();
733
            row.add(priceCircularItemModel.getCatalogId());
734
            row.add(brand);
735
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelName());
736
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelNumber());
737
            //TODO: fix nlc
738
            //row.add(priceCircularItemModel.getNetPrice());
739
            rows.add(row);
740
        }
741
        return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
742
    }
30471 amit.gupta 743
 
31903 amit.gupta 744
    @RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
745
    public String selectPriceDropStatus(HttpServletRequest request,
746
                                        @RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
747
                                        Model model) throws Exception {
30250 amit.gupta 748
 
31903 amit.gupta 749
        model.addAttribute("selectedStatus", selectedStatus);
750
        return "pricedrop-status-change";
751
    }
30250 amit.gupta 752
 
23819 govind 753
}