Subversion Repositories SmartDukaan

Rev

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