Subversion Repositories SmartDukaan

Rev

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