Subversion Repositories SmartDukaan

Rev

Rev 32331 | Rev 32844 | 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
        priceDropService.processPriceDrop(priceDrop.getId(), priceDropProcessModel.isActivatedOnly());
285
        response = true;
286
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
287
        return "response";
288
    }
28102 tejbeer 289
 
31903 amit.gupta 290
    @RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
291
    public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
292
            throws Exception {
293
        boolean response = false;
294
        priceDropModel.setAllColors(true);
295
        if (this.validatePriceDrop(priceDropModel)) {
296
            TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
297
            float oldDp = tagListing.getSellingPrice();
298
            float oldMop = tagListing.getMop();
299
            float oldTp = 0;
300
            float newDp = priceDropModel.getDp();
28102 tejbeer 301
 
31903 amit.gupta 302
            if (newDp != oldDp) {
303
                List<Item> allItems = null;
304
                Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
305
                if (priceDropModel.isAllColors()) {
306
                    allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
28102 tejbeer 307
 
31903 amit.gupta 308
                } else {
309
                    allItems = Arrays.asList(currentItem);
310
                }
311
                for (Item item : allItems) {
312
                    TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
313
                    if (itemTagListing == null)
314
                        continue;
315
                    itemTagListing.setSellingPrice(newDp);
316
                    itemTagListing.setMop(priceDropModel.getMop());
317
                    List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
318
                    for (VendorItemPricing vip : vipList) {
319
                        oldTp = vip.getNlc();
320
                        vip.setDp(newDp);
321
                        vip.setMop(priceDropModel.getMop());
322
                        //Lets not update NLC/TP as it has to be managed by Category Tea,
323
                        //vip.setNlc(priceDropModel.getTp());
324
                        //vip.setTp(priceDropModel.getTp());
325
                        vendorItemPricingRepository.persist(vip);
326
                    }
327
                    transactionService.updatePriceDrop(item.getId(), newDp);
328
                }
29926 amit.gupta 329
 
31903 amit.gupta 330
                // Add to itemPricing history
331
                ItemPricingHistory iph = new ItemPricingHistory();
332
                iph.setCatalogId(currentItem.getCatalogItemId());
333
                iph.setTp(priceDropModel.getTp());
334
                iph.setDp(priceDropModel.getDp());
335
                iph.setMop(priceDropModel.getMop());
336
                // TODO: changedBy
337
                iph.setChangedBy("me");
338
                iph.setCreateTimestamp(LocalDateTime.now());
339
                itemPricingHistoryRepository.persist(iph);
28136 tejbeer 340
 
31903 amit.gupta 341
                PriceDrop priceDrop = new PriceDrop();
342
                priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
343
                priceDrop.setTp(oldTp);
344
                priceDrop.setNlc(oldTp);
345
                priceDrop.setMop(oldMop);
346
                priceDrop.setOldDp(oldDp);
347
                priceDrop.setAmount(oldDp - newDp);
348
                priceDrop.setNewDp(newDp);
349
                priceDrop.setCreatedOn(LocalDateTime.now());
350
                priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
351
                priceDropRepository.persist(priceDrop);
352
                priceDropService.priceDropStatus(priceDrop.getId());
353
                response = true;
30471 amit.gupta 354
 
31903 amit.gupta 355
                this.sendPriceChangeNotification(priceDrop);
356
            } else {
357
                throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
358
                        "Price Drop Should be greater than 0");
359
            }
360
        }
361
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
362
        return "response";
363
    }
29654 tejbeer 364
 
31903 amit.gupta 365
    private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
366
        List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
367
        String title = "Price has been %s for %s";
24083 amit.gupta 368
 
28568 amit.gupta 369
 
31903 amit.gupta 370
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
371
        sendNotificationModel.setCampaignName("pricechange");
372
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
373
        sendNotificationModel.setTitle("");
374
        StringBuffer sb = new StringBuffer();
375
        String message = null;
376
        if (priceDrop.getDropAmount() > 0) {
377
            title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
378
            message = String.format("Price has been dropped from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(priceDrop.getDropAmount()),
379
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
380
        } else {
381
            title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
382
            message = String.format("Price has been increased from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(-priceDrop.getDropAmount()),
383
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
384
        }
385
        sendNotificationModel.setTitle(title);
386
        sendNotificationModel.setMessage(message);
387
        sendNotificationModel.setMessageType(MessageType.pricechange);
388
        notificationService.sendNotificationToAll(sendNotificationModel);
389
    }
28568 amit.gupta 390
 
31903 amit.gupta 391
    @RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
392
    public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
393
                                                        Model model) throws ProfitMandiBusinessException, Exception {
28568 amit.gupta 394
 
31903 amit.gupta 395
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
396
        Map<String, PriceDropIMEI> priceDropIMEIsMap = priceDropIMEIRepository.selectByPriceDropId(priceDropId).stream()
397
                .collect(Collectors.toMap(x -> x.getImei(), x -> x));
398
        LOGGER.info("PriceDropImeis {}, priceDropId {}", priceDropIMEIsMap, priceDropId);
399
        Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
400
        final HttpHeaders headers = new HttpHeaders();
401
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
402
        headers.set("Content-disposition",
403
                "inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
404
                        + FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
405
        ByteArrayOutputStream baos = null;
406
        if (priceDropIMEIsMap.size() == 0) {
407
            priceDropService.priceDropStatus(priceDrop.getId());
408
            baos = FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
409
                    "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
410
                    "Grn On", "Activation Timestamp", "Activation Added On"), new ArrayList<>());
411
        } else {
28568 amit.gupta 412
 
31903 amit.gupta 413
            LOGGER.info("In else block");
414
            baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(),
415
                    priceDropIMEIsMap);
416
        }
417
        byte[] byteArray = baos.toByteArray();
418
        headers.setContentLength(byteArray.length);
419
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
24083 amit.gupta 420
 
31903 amit.gupta 421
    }
24083 amit.gupta 422
 
31903 amit.gupta 423
    @RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
424
    public String updatePriceDropImeis(HttpServletRequest request, @RequestBody PriceDropImeisModel priceDropImeisModel,
425
                                       Model model) throws ProfitMandiBusinessException, Exception {
32012 amit.gupta 426
        final PriceDropImeiStatus status;
28102 tejbeer 427
 
31903 amit.gupta 428
        switch (priceDropImeisModel.getUpdatedStatus()) {
429
            case "approved": {
430
                status = PriceDropImeiStatus.APPROVED;
431
                break;
432
            }
32012 amit.gupta 433
            case "pending": {
434
                status = PriceDropImeiStatus.PENDING;
31903 amit.gupta 435
                break;
436
            }
437
            case "rejected": {
438
                status = PriceDropImeiStatus.REJECTED;
439
                break;
440
            }
32012 amit.gupta 441
            case "hold": {
442
                status = PriceDropImeiStatus.HOLD;
443
                break;
444
            }
445
            default:
446
                throw new IllegalStateException("Unexpected value: " + priceDropImeisModel.getUpdatedStatus());
31903 amit.gupta 447
        }
24168 amit.gupta 448
 
31903 amit.gupta 449
        if (PriceDropImeiStatus.PENDING.equals(status)) {
32012 amit.gupta 450
            List<PriceDropIMEI> priceDropIMEIsToPending = new ArrayList<>();
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
                priceDropIMEIsToPending.add(priceDropIMEI);
459
                priceDropIMEI.setStatus(PriceDropImeiStatus.PENDING);
31903 amit.gupta 460
            }
461
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
462
            return "response";
463
        }
23951 amit.gupta 464
 
32012 amit.gupta 465
        if (status.equals(PriceDropImeiStatus.APPROVED)) {
466
            priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
467
                    priceDropImeisModel.getUpdatedImeis());
468
        }
469
 
31903 amit.gupta 470
        List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
471
                .selectByPriceDropId(priceDropImeisModel.getPriceDropId());
472
        List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
473
                .filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
32012 amit.gupta 474
                .filter(x -> !x.getStatus().equals(status)).collect(Collectors.toList());
31903 amit.gupta 475
        for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
476
            if (status.equals(PriceDropImeiStatus.REJECTED)
477
                    && priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
478
                priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
479
                priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
480
                priceDropImei.setRejectTimestamp(LocalDateTime.now());
481
            } else if (status.equals(PriceDropImeiStatus.HOLD)) {
482
                if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
483
                    priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
484
                } else {
485
                    throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
486
                }
28568 amit.gupta 487
 
31903 amit.gupta 488
            }
28568 amit.gupta 489
 
31903 amit.gupta 490
        }
28568 amit.gupta 491
 
31903 amit.gupta 492
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
493
        return "response";
24083 amit.gupta 494
 
31903 amit.gupta 495
    }
24083 amit.gupta 496
 
31903 amit.gupta 497
    private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
498
                                                           Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
499
        List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
500
                .getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
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
 
31903 amit.gupta 547
    @RequestMapping(value = "/priceCircular")
548
    public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
549
        int fofoId = Utils.SYSTEM_PARTNER_ID;
550
        Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
551
                .collect(Collectors.toSet());
552
        brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
553
                .collect(Collectors.toSet()));
28102 tejbeer 554
 
31903 amit.gupta 555
        model.addAttribute("brands", brands);
556
        model.addAttribute("isAdmin", true);
557
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 558
 
31903 amit.gupta 559
        return "partner-price-circular";
560
    }
28102 tejbeer 561
 
31903 amit.gupta 562
    @RequestMapping(value = "/partnerPriceCircular")
563
    public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
564
        int fofoId = Utils.SYSTEM_PARTNER_ID;
565
        Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
566
                .collect(Collectors.toSet());
567
        brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
568
                .collect(Collectors.toSet()));
569
        model.addAttribute("brands", brands);
570
        model.addAttribute("isAdmin", false);
28102 tejbeer 571
 
31903 amit.gupta 572
        return "partner-price-circular";
573
    }
28102 tejbeer 574
 
31903 amit.gupta 575
    @RequestMapping(value = "/priceCircularByBrand")
576
    public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
577
            throws ProfitMandiBusinessException {
578
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
579
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
580
        } else {
581
            fofoId = loginDetails.getFofoId();
582
        }
583
        //.minusDays(2)
584
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
32331 amit.gupta 585
        return this.getPriceCircularView(priceCircular, model);
586
    }
587
 
588
    public String getPriceCircularView(PriceCircularModel priceCircular, Model model) throws ProfitMandiBusinessException {
31903 amit.gupta 589
        List<String> schemeHeaders = new ArrayList<>(this.getSchemeHeaders(priceCircular));
590
        List<String> allMargins = ALL_MARGINS.stream().filter(x -> schemeHeaders.contains(x)).collect(Collectors.toList());
591
        List<String> sellins = SELLINS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
592
        List<String> sellouts = SELLOUTS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
593
        LOGGER.info("Scheme Headers = {}", schemeHeaders);
594
        LOGGER.info("allMargins {}", allMargins);
595
        LOGGER.info("Sellins - {}", sellins);
596
        LOGGER.info("Sellouts - {}", sellouts);
597
        model.addAttribute("priceCircularItemModels", priceCircular.getPriceCircularItemModelNews());
598
        model.addAttribute("allMargins", allMargins);
599
        model.addAttribute("sellins", sellins);
600
        model.addAttribute("sellouts", sellouts);
601
        model.addAttribute("offers", priceCircular.getOffers());
602
        model.addAttribute("upgradeOffer", priceCircular.isUpgradeOffer());
603
        model.addAttribute("mvcResponseSender", mvcResponseSender);
32331 amit.gupta 604
        return "price-circular-table";
31903 amit.gupta 605
    }
29951 amit.gupta 606
 
31903 amit.gupta 607
    private Set<String> getSchemeHeaders(PriceCircularModel priceCircular) {
608
        Set<String> schemeHeaders = new HashSet<>();
609
        priceCircular.getPriceCircularItemModelNews().stream().forEach(priceCircularItemModelNew -> {
610
            Map<String, AmountModel> headerMap = new HashMap<>();
611
            priceCircularItemModelNew.setHeaderSchemeModelsMap(headerMap);
612
            priceCircularItemModelNew.getSchemeSummaryModels().stream().forEach(schemeSummaryModel -> {
613
                if (schemeSummaryModel == null) return;
614
                if (schemeSummaryModel.getSchemeType().equals(SchemeType.SPECIAL_SUPPORT) || schemeSummaryModel.getSchemeType().equals(SchemeType.ACTIVATION)) {
615
                    schemeSummaryModel.setHeader("Special Support");
616
                } else if (schemeSummaryModel.getDescription().equalsIgnoreCase("modelwise") && schemeSummaryModel.getSchemeType().equals(SchemeType.IN)) {
617
                    schemeSummaryModel.setHeader("Modelwise");
31911 amit.gupta 618
                } else if (schemeSummaryModel.getSchemeType().equals(SchemeType.IN)) {
619
                    schemeSummaryModel.setHeader(schemeSummaryModel.getDescription());
31903 amit.gupta 620
                } else {
31910 amit.gupta 621
                    schemeSummaryModel.setHeader(schemeSummaryModel.getSchemeType().getValue());
31903 amit.gupta 622
                }
623
                if (!headerMap.containsKey(schemeSummaryModel.getHeader())) {
624
                    headerMap.put(schemeSummaryModel.getHeader(), new AmountModel(schemeSummaryModel.getAmount(), schemeSummaryModel.getAmountType()));
625
                } else {
626
                    AmountModel model = headerMap.get(schemeSummaryModel.getHeader());
627
                    model.setAmount(model.getAmount() + schemeSummaryModel.getAmount());
628
                }
629
                schemeHeaders.add(schemeSummaryModel.getHeader());
630
            });
631
        });
28102 tejbeer 632
 
31903 amit.gupta 633
        LOGGER.info("Scheme headers - {}", schemeHeaders);
634
        return schemeHeaders;
635
    }
30250 amit.gupta 636
 
31903 amit.gupta 637
    //private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
638
    //private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
30471 amit.gupta 639
 
30562 amit.gupta 640
 
31903 amit.gupta 641
    @RequestMapping(value = "/downloadNlcByBrand")
642
    public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
643
                                                                @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
644
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
645
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
646
        } else {
647
            fofoId = loginDetails.getFofoId();
648
        }
649
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
650
        /*List<Integer> catalogIds = priceCircular.getPriceCircularItemModelNews().stream().limit(10).map(x->x.getCatalogId()).collect(Collectors.toList());
651
        priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());*/
652
        ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
653
        final HttpHeaders headers = new HttpHeaders();
654
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
655
        headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
656
        byte[] byteArray = baos.toByteArray();
657
        headers.setContentLength(byteArray.length);
658
        return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
659
    }
30471 amit.gupta 660
 
31903 amit.gupta 661
    private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
662
        List<List<?>> rows = new ArrayList<>();
663
        for (PriceCircularItemModelNew priceCircularItemModel : priceCircular.getPriceCircularItemModelNews()) {
664
            List<Serializable> row = new ArrayList<>();
665
            row.add(priceCircularItemModel.getCatalogId());
666
            row.add(brand);
667
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelName());
668
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelNumber());
669
            //TODO: fix nlc
670
            //row.add(priceCircularItemModel.getNetPrice());
671
            rows.add(row);
672
        }
673
        return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
674
    }
30471 amit.gupta 675
 
31903 amit.gupta 676
    @RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
677
    public String selectPriceDropStatus(HttpServletRequest request,
678
                                        @RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
679
                                        Model model) throws Exception {
30250 amit.gupta 680
 
31903 amit.gupta 681
        model.addAttribute("selectedStatus", selectedStatus);
682
        return "pricedrop-status-change";
683
    }
30250 amit.gupta 684
 
23819 govind 685
}