Subversion Repositories SmartDukaan

Rev

Rev 31852 | Rev 31910 | 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;
28136 tejbeer 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;
23819 govind 35
import com.spice.profitmandi.service.inventory.InventoryService;
31903 amit.gupta 36
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModelNew;
29788 amit.gupta 37
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
38
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
23983 amit.gupta 39
import com.spice.profitmandi.service.pricing.PriceDropService;
23968 amit.gupta 40
import com.spice.profitmandi.service.scheme.SchemeService;
23884 amit.gupta 41
import com.spice.profitmandi.service.transaction.TransactionService;
28102 tejbeer 42
import com.spice.profitmandi.service.user.RetailerService;
23819 govind 43
import com.spice.profitmandi.service.wallet.WalletService;
28102 tejbeer 44
import com.spice.profitmandi.web.model.LoginDetails;
45
import com.spice.profitmandi.web.util.CookiesProcessor;
23819 govind 46
import com.spice.profitmandi.web.util.MVCResponseSender;
29926 amit.gupta 47
import org.apache.commons.io.output.ByteArrayOutputStream;
48
import org.apache.logging.log4j.LogManager;
49
import org.apache.logging.log4j.Logger;
50
import org.springframework.beans.factory.annotation.Autowired;
51
import org.springframework.beans.factory.annotation.Qualifier;
52
import org.springframework.core.io.ByteArrayResource;
53
import org.springframework.http.HttpHeaders;
54
import org.springframework.http.HttpStatus;
55
import org.springframework.http.ResponseEntity;
56
import org.springframework.stereotype.Controller;
57
import org.springframework.transaction.annotation.Transactional;
58
import org.springframework.ui.Model;
59
import org.springframework.web.bind.annotation.*;
23819 govind 60
 
29926 amit.gupta 61
import javax.servlet.http.HttpServletRequest;
62
import java.io.Serializable;
63
import java.time.LocalDate;
64
import java.time.LocalDateTime;
65
import java.util.*;
66
import java.util.stream.Collectors;
67
 
23819 govind 68
@Controller
27071 amit.gupta 69
@Transactional(rollbackFor = Throwable.class)
23819 govind 70
public class PriceDropController {
71
 
31903 amit.gupta 72
    private static final Logger LOGGER = LogManager.getLogger(PriceDropController.class);
73
    private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin", "Modelwise");
74
    private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
75
    private static final List<String> ALL_MARGINS = Arrays.asList(SELLINS, SELLOUTS).stream().flatMap(x -> x.stream()).collect(Collectors.toList());
76
    @Autowired
77
    ReporticoService reporticoService;
78
    @Autowired
79
    LineItemImeisRepository lineItemImeisRepository;
80
    @Autowired
81
    PriceCircularService priceCircularService;
82
    @Autowired
83
    private CsService csService;
84
    @Autowired
85
    private UserRepository dtrUserRepository;
86
    @Autowired
87
    private PriceDropRepository priceDropRepository;
88
    @Autowired
89
    private ObjectMapper objectMapper;
90
    @Autowired
91
    private VendorItemPricingRepository vendorItemPricingRepository;
92
    @Autowired
93
    @Qualifier("fofoInventoryService")
94
    private InventoryService inventoryService;
95
    @Autowired
96
    private MVCResponseSender mvcResponseSender;
97
    @Autowired
98
    private PriceDropService priceDropService;
99
    @Autowired
100
    private ItemPricingHistoryRepository itemPricingHistoryRepository;
101
    @Autowired
102
    private WalletService walletService;
103
    @Autowired
104
    private TagListingRepository tagListingRepository;
105
    @Autowired
106
    private TransactionService transactionService;
107
    @Autowired
108
    private PriceDropIMEIRepository priceDropIMEIRepository;
109
    @Autowired
110
    private RoleManager roleManager;
111
    @Autowired
112
    @Qualifier("catalogItemRepository")
113
    private ItemRepository itemRepository;
114
    @Autowired
115
    private SchemeService schemeService;
116
    @Autowired
117
    private Mongo mongoClient;
118
    @Autowired
119
    private CookiesProcessor cookiesProcessor;
120
    @Autowired
121
    private PartnerTypeChangeService partnerTypeChangeService;
122
    @Autowired
123
    private RetailerService retailerService;
124
    @Autowired
125
    private NotificationService notificationService;
126
    @Autowired
127
    private FofoStoreRepository fofoStoreRepository;
23819 govind 128
 
31903 amit.gupta 129
    @RequestMapping(value = "/getItemDescription", method = RequestMethod.GET)
130
    public String getItemDescription(HttpServletRequest request, Model model) throws Throwable {
131
        List<PriceDrop> priceDrops = priceDropRepository.selectAllIncomplete();
132
        Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
29926 amit.gupta 133
 
31903 amit.gupta 134
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
135
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
136
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
137
        model.addAttribute("priceDrops", priceDrops);
138
        model.addAttribute("catalogDescription", catalogDescription);
139
        return "price-drop";
140
    }
29926 amit.gupta 141
 
31903 amit.gupta 142
    @RequestMapping(value = "/getClosedPricedropItemDescription", method = RequestMethod.GET)
143
    public String getClosedPricedropItemDescription(HttpServletRequest request, Model model) throws Throwable {
144
        List<PriceDrop> priceDrops = priceDropRepository.selectAllComplete();
145
        int processOn = 1;
23819 govind 146
 
31903 amit.gupta 147
        List<PriceDrop> completePriceDrops = priceDrops.stream().filter(x -> x.getCompleteTimestamp() != null)
148
                .collect(Collectors.toList());
23945 amit.gupta 149
 
31903 amit.gupta 150
        Set<Integer> catalogIds = completePriceDrops.stream().map(x -> x.getCatalogItemId())
151
                .collect(Collectors.toSet());
152
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
153
        LOGGER.info("catalogIds" + catalogIds);
23819 govind 154
 
31903 amit.gupta 155
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
156
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
157
        model.addAttribute("priceDrops", completePriceDrops);
158
        model.addAttribute("processOn", processOn);
159
        model.addAttribute("catalogDescription", catalogDescription);
160
        return "price-drop";
161
    }
23945 amit.gupta 162
 
31903 amit.gupta 163
    @RequestMapping(value = "/item-pricing/{itemId}", method = RequestMethod.GET)
164
    public String getItemPricing(HttpServletRequest request, Model model, @PathVariable int itemId) throws Throwable {
23819 govind 165
 
31903 amit.gupta 166
        TagListing tagListing;
167
        PriceDropModel pm = new PriceDropModel();
168
        try {
169
            tagListing = tagListingRepository.selectByItemId(itemId);
170
            if (tagListing != null) {
171
                pm.setMop(tagListing.getMop());
172
                pm.setDp(tagListing.getSellingPrice());
173
                pm.setMrp(tagListing.getMrp());
174
                List<VendorItemPricing> vips = vendorItemPricingRepository.selectAll(itemId);
175
                if (vips.size() > 0) {
176
                    VendorItemPricing vip = vips.get(0);
177
                    pm.setNlc(vip.getNlc());
178
                    pm.setTp(vip.getTp());
179
                } else {
180
                    throw new ProfitMandiBusinessException("Item Id", itemId, "Vendor item pricing does not exist");
181
                }
182
            }
183
        } catch (Exception e) {
184
            LOGGER.info("Chose item that doesn't exist");
185
        }
186
        model.addAttribute("response1", mvcResponseSender.createResponseString(pm));
187
        return "response";
188
    }
27071 amit.gupta 189
 
31903 amit.gupta 190
    @RequestMapping(value = "/item", method = RequestMethod.GET)
191
    public String getItemPricing(HttpServletRequest request, Model model, @RequestParam String query,
192
                                 @RequestParam boolean anyColor) throws Throwable {
193
        String query1 = query.toLowerCase();
24083 amit.gupta 194
 
31903 amit.gupta 195
        List<ItemDescriptionModel> partnersItemDescription = inventoryService
196
                .getAllPartnerItemStringDescription(anyColor).parallelStream()
197
                .filter(x -> x.getItemDescription().toLowerCase().matches(".*?" + query1 + ".*?"))
198
                .collect(Collectors.toList());
199
        LOGGER.info("partnersItemDescription" + partnersItemDescription);
23819 govind 200
 
31903 amit.gupta 201
        model.addAttribute("response1", mvcResponseSender.createResponseString(partnersItemDescription));
202
        return "response";
203
    }
23945 amit.gupta 204
 
31903 amit.gupta 205
    @RequestMapping(value = "/price-drop/imes/download")
206
    public ResponseEntity<ByteArrayResource> downloadPriceDropImeis(HttpServletRequest request,
207
                                                                    @RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws Exception {
208
        Item item = itemRepository.selectById(itemId);
209
        ByteArrayOutputStream baos = getByteArrayOutputStream(affectedDate, item.getCatalogItemId(), null);
210
        final HttpHeaders headers = new HttpHeaders();
211
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
212
        headers.set("Content-disposition", "inline; filename=\"imei-" + item.getItemDescriptionNoColor() + ".csv\"");
213
        byte[] byteArray = baos.toByteArray();
214
        headers.setContentLength(byteArray.length);
215
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
216
    }
23819 govind 217
 
31903 amit.gupta 218
    @RequestMapping(value = "/price-drop/addPayout", method = RequestMethod.POST)
219
    public String updatePriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
220
                                  Model model) throws Exception {
221
        boolean response = false;
222
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
223
        if (priceDrop.getProcessTimestamp() == null) {
224
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
225
            priceDrop.setPriceDropIn(priceDropProcessModel.getPriceDropIn());
226
            // priceDrop.setProcessTimestamp(LocalDateTime.now());
227
            priceDropRepository.persist(priceDrop);
228
            response = true;
229
        }
230
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
231
        return "response";
232
    }
24083 amit.gupta 233
 
31903 amit.gupta 234
    @RequestMapping(value = "/priceDropImeis/{priceDropId}", method = RequestMethod.GET)
235
    public String priceDropStatus(HttpServletRequest request, @PathVariable int priceDropId, Model model)
236
            throws Exception {
29951 amit.gupta 237
 
31903 amit.gupta 238
        PriceDropImeisModel priceDropImeisModel = new PriceDropImeisModel();
23819 govind 239
 
31903 amit.gupta 240
        // This call is used to persit imeis to pricedrop imeis in case its not there.
241
        // This should be called while creating price drop.
242
        // priceDropService.priceDropStatus(priceDropId);
24083 amit.gupta 243
 
31903 amit.gupta 244
        List<String> pendingImeis = new ArrayList<>();
245
        List<String> approvedImeis = new ArrayList<>();
246
        List<String> rejectedImeis = new ArrayList<>();
247
        List<String> holdImeis = new ArrayList<>();
248
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
249
        for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
250
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.PENDING)) {
251
                pendingImeis.add(priceDropIMEI.getImei());
252
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)) {
253
                approvedImeis.add(priceDropIMEI.getImei());
254
            }
255
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.REJECTED)) {
256
                rejectedImeis.add(priceDropIMEI.getImei());
257
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
258
                holdImeis.add(priceDropIMEI.getImei());
24083 amit.gupta 259
 
31903 amit.gupta 260
            }
261
        }
262
        LOGGER.info("pendingImeis" + pendingImeis);
263
        LOGGER.info("approvedImeis" + approvedImeis);
264
        LOGGER.info("rejectedImeis" + rejectedImeis);
265
        LOGGER.info("priceDropImeis" + priceDropImeis);
23945 amit.gupta 266
 
31903 amit.gupta 267
        priceDropImeisModel.setPendingImeis(pendingImeis);
268
        priceDropImeisModel.setPriceDropId(priceDropId);
269
        priceDropImeisModel.setApprovedImeis(approvedImeis);
270
        priceDropImeisModel.setHoldImeis(holdImeis);
271
        priceDropImeisModel.setRejectedImeis(rejectedImeis);
272
        model.addAttribute("response1", mvcResponseSender.createResponseString(priceDropImeisModel));
273
        return "response";
274
    }
28102 tejbeer 275
 
31903 amit.gupta 276
    @RequestMapping(value = "/processPriceDrop", method = RequestMethod.POST)
277
    public String processPriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
278
                                   Model model) throws Exception {
279
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
280
        boolean response = false;
281
        if (priceDrop.getPartnerPayout() == 0) {
282
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
283
        }
284
        priceDrop.setProcessTimestamp(LocalDateTime.now());
285
        priceDropRepository.persist(priceDrop);
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");
416
            baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(),
417
                    priceDropIMEIsMap);
418
        }
419
        byte[] byteArray = baos.toByteArray();
420
        headers.setContentLength(byteArray.length);
421
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
24083 amit.gupta 422
 
31903 amit.gupta 423
    }
24083 amit.gupta 424
 
31903 amit.gupta 425
    @RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
426
    public String updatePriceDropImeis(HttpServletRequest request, @RequestBody PriceDropImeisModel priceDropImeisModel,
427
                                       Model model) throws ProfitMandiBusinessException, Exception {
428
        PriceDropImeiStatus status = PriceDropImeiStatus.PENDING;
28102 tejbeer 429
 
31903 amit.gupta 430
        switch (priceDropImeisModel.getUpdatedStatus()) {
431
            case "approved": {
432
                status = PriceDropImeiStatus.APPROVED;
433
                break;
434
            }
435
            case "hold": {
436
                status = PriceDropImeiStatus.HOLD;
437
                break;
438
            }
439
            case "rejected": {
440
                status = PriceDropImeiStatus.REJECTED;
441
                break;
442
            }
443
        }
444
        PriceDropImeiStatus finalStatus = status;
24168 amit.gupta 445
 
31903 amit.gupta 446
        if (PriceDropImeiStatus.PENDING.equals(status)) {
24168 amit.gupta 447
 
31903 amit.gupta 448
            List<PriceDropIMEI> priceDropIMEIsToHolds = new ArrayList<>();
449
            List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByIdAndStatus(PriceDropImeiStatus.HOLD,
450
                    priceDropImeisModel.getPriceDropId());
451
            LOGGER.info("hello" + priceDropIMEIs);
452
            for (PriceDropIMEI priceDropHoldIMEI : priceDropIMEIs) {
453
                if (priceDropHoldIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
454
                    if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropHoldIMEI.getImei())
455
                            || priceDropHoldIMEI.getStatus().equals(status)) {
456
                        continue;
457
                    }
458
                    priceDropIMEIsToHolds.add(priceDropHoldIMEI);
459
                    priceDropHoldIMEI.setStatus(PriceDropImeiStatus.PENDING);
460
                    //priceDropHoldIMEI.setUpdateTimestamp(LocalDateTime.now());
461
                } else {
462
                    throw new ProfitMandiBusinessException("INVALID STATUS", "PENDING",
463
                            "Pending Status is allowed  only for Hold IMIEs");
464
                }
465
            }
466
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
467
            return "response";
468
        }
23951 amit.gupta 469
 
31903 amit.gupta 470
        // TODO:PD
471
        List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
472
                .selectByPriceDropId(priceDropImeisModel.getPriceDropId());
24083 amit.gupta 473
 
31903 amit.gupta 474
        List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
475
                .filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
476
                .filter(x -> !x.getStatus().equals(finalStatus)).collect(Collectors.toList());
24083 amit.gupta 477
 
31852 amit.gupta 478
        /*for (PriceDropIMEI priceDropIMEI : priceDropIMEIsToProcess) {
26368 amit.gupta 479
			priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
31009 amit.gupta 480
		}*/
28568 amit.gupta 481
 
31903 amit.gupta 482
        if (status.equals(PriceDropImeiStatus.APPROVED)) {
483
            priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
484
                    priceDropImeisModel.getUpdatedImeis());
485
        }
486
        for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
487
            if (status.equals(PriceDropImeiStatus.REJECTED)
488
                    && priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
489
                priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
490
                priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
491
                priceDropImei.setRejectTimestamp(LocalDateTime.now());
492
            } else if (status.equals(PriceDropImeiStatus.HOLD)) {
493
                if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
494
                    priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
495
                } else {
496
                    throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
497
                }
28568 amit.gupta 498
 
31903 amit.gupta 499
            }
28568 amit.gupta 500
 
31903 amit.gupta 501
        }
28568 amit.gupta 502
 
31903 amit.gupta 503
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
504
        return "response";
24083 amit.gupta 505
 
31903 amit.gupta 506
    }
24083 amit.gupta 507
 
31903 amit.gupta 508
    private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
509
                                                           Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
510
        List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
511
                .getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
512
        List<List<?>> rows = new ArrayList<>();
513
        for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
514
            if (priceDropImeis == null) {
515
                rows.add(this.getRow(imeiDropSummaryModel, null));
516
            } else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
517
                rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
518
            }
519
        }
520
        return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
521
                "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
522
                "Grn On", "Activation Timestamp", "Activation Added On"), rows);
523
    }
24083 amit.gupta 524
 
31903 amit.gupta 525
    private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
526
                                                PriceDropIMEI priceDropIMEI) {
527
        List<Serializable> row = new ArrayList<>();
528
        row.add(imeiDropSummaryModel.getSerialNumber());
529
        row.add(imeiDropSummaryModel.getStoreName());
530
        row.add(imeiDropSummaryModel.getPartnerCode());
531
        row.add(imeiDropSummaryModel.getItemId());
532
        row.add(imeiDropSummaryModel.getBrand());
533
        row.add(imeiDropSummaryModel.getModelName());
534
        row.add(imeiDropSummaryModel.getModelNumber());
535
        row.add(imeiDropSummaryModel.getColor());
536
        if (priceDropIMEI != null) {
537
            row.add(priceDropIMEI.getStatus());
538
            row.add(priceDropIMEI.getRejectionReason());
539
        } else {
540
            row.add(PriceDropImeiStatus.PENDING);
541
            row.add("");
542
        }
543
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
544
        row.add(imeiDropSummaryModel.getVendorName());
545
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
546
        row.add(imeiDropSummaryModel.getActivationTimestamp());
547
        row.add(imeiDropSummaryModel.getActivationAddedOn());
548
        return row;
549
    }
23819 govind 550
 
31903 amit.gupta 551
    private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
552
        if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
553
            return true;
554
        }
555
        return false;
556
    }
23945 amit.gupta 557
 
31903 amit.gupta 558
    @RequestMapping(value = "/priceCircular")
559
    public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
560
        int fofoId = Utils.SYSTEM_PARTNER_ID;
561
        Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
562
                .collect(Collectors.toSet());
563
        brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
564
                .collect(Collectors.toSet()));
28102 tejbeer 565
 
31903 amit.gupta 566
        model.addAttribute("brands", brands);
567
        model.addAttribute("isAdmin", true);
568
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 569
 
31903 amit.gupta 570
        return "partner-price-circular";
571
    }
28102 tejbeer 572
 
31903 amit.gupta 573
    @RequestMapping(value = "/partnerPriceCircular")
574
    public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
575
        int fofoId = Utils.SYSTEM_PARTNER_ID;
576
        Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
577
                .collect(Collectors.toSet());
578
        brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
579
                .collect(Collectors.toSet()));
580
        model.addAttribute("brands", brands);
581
        model.addAttribute("isAdmin", false);
28102 tejbeer 582
 
31903 amit.gupta 583
        return "partner-price-circular";
584
    }
28102 tejbeer 585
 
31903 amit.gupta 586
    @RequestMapping(value = "/priceCircularByBrand")
587
    public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
588
            throws ProfitMandiBusinessException {
589
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
590
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
591
        } else {
592
            fofoId = loginDetails.getFofoId();
593
        }
594
        //.minusDays(2)
595
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
596
        //List<Integer> catalogIds = priceCircular.getPriceCircularItemModelNews().stream().limit(100).map(x->x.getCatalogId()).collect(Collectors.toList());
597
        //priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
598
        List<String> schemeHeaders = new ArrayList<>(this.getSchemeHeaders(priceCircular));
599
        List<String> allMargins = ALL_MARGINS.stream().filter(x -> schemeHeaders.contains(x)).collect(Collectors.toList());
600
        List<String> sellins = SELLINS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
601
        List<String> sellouts = SELLOUTS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
602
        LOGGER.info("Scheme Headers = {}", schemeHeaders);
603
        LOGGER.info("allMargins {}", allMargins);
604
        LOGGER.info("Sellins - {}", sellins);
605
        LOGGER.info("Sellouts - {}", sellouts);
606
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
607
        model.addAttribute("priceCircularItemModels", priceCircular.getPriceCircularItemModelNews());
608
        model.addAttribute("allMargins", allMargins);
609
        model.addAttribute("sellins", sellins);
610
        model.addAttribute("sellouts", sellouts);
611
        model.addAttribute("offers", priceCircular.getOffers());
612
        model.addAttribute("upgradeOffer", priceCircular.isUpgradeOffer());
613
        model.addAttribute("partnerCode", fs.getCode());
614
        model.addAttribute("mvcResponseSender", mvcResponseSender);
615
        return "price-circular-detail";
616
    }
29951 amit.gupta 617
 
31903 amit.gupta 618
    private Set<String> getSchemeHeaders(PriceCircularModel priceCircular) {
619
        Set<String> schemeHeaders = new HashSet<>();
620
        priceCircular.getPriceCircularItemModelNews().stream().forEach(priceCircularItemModelNew -> {
621
            Map<String, AmountModel> headerMap = new HashMap<>();
622
            priceCircularItemModelNew.setHeaderSchemeModelsMap(headerMap);
623
            priceCircularItemModelNew.getSchemeSummaryModels().stream().forEach(schemeSummaryModel -> {
624
                if (schemeSummaryModel == null) return;
625
                if (schemeSummaryModel.getSchemeType().equals(SchemeType.SPECIAL_SUPPORT) || schemeSummaryModel.getSchemeType().equals(SchemeType.ACTIVATION)) {
626
                    schemeSummaryModel.setHeader("Special Support");
627
                } else if (schemeSummaryModel.getDescription().equalsIgnoreCase("modelwise") && schemeSummaryModel.getSchemeType().equals(SchemeType.IN)) {
628
                    schemeSummaryModel.setHeader("Modelwise");
629
                } else {
630
                    schemeSummaryModel.setHeader(schemeSummaryModel.getDescription());
631
                }
632
                if (!headerMap.containsKey(schemeSummaryModel.getHeader())) {
633
                    headerMap.put(schemeSummaryModel.getHeader(), new AmountModel(schemeSummaryModel.getAmount(), schemeSummaryModel.getAmountType()));
634
                } else {
635
                    AmountModel model = headerMap.get(schemeSummaryModel.getHeader());
636
                    model.setAmount(model.getAmount() + schemeSummaryModel.getAmount());
637
                }
638
                schemeHeaders.add(schemeSummaryModel.getHeader());
639
            });
640
        });
28102 tejbeer 641
 
31903 amit.gupta 642
        LOGGER.info("Scheme headers - {}", schemeHeaders);
643
        return schemeHeaders;
644
    }
30250 amit.gupta 645
 
31903 amit.gupta 646
    //private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
647
    //private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
30471 amit.gupta 648
 
30562 amit.gupta 649
 
31903 amit.gupta 650
    @RequestMapping(value = "/downloadNlcByBrand")
651
    public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
652
                                                                @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
653
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
654
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
655
        } else {
656
            fofoId = loginDetails.getFofoId();
657
        }
658
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
659
        /*List<Integer> catalogIds = priceCircular.getPriceCircularItemModelNews().stream().limit(10).map(x->x.getCatalogId()).collect(Collectors.toList());
660
        priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());*/
661
        ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
662
        final HttpHeaders headers = new HttpHeaders();
663
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
664
        headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
665
        byte[] byteArray = baos.toByteArray();
666
        headers.setContentLength(byteArray.length);
667
        return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
668
    }
30471 amit.gupta 669
 
31903 amit.gupta 670
    private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
671
        List<List<?>> rows = new ArrayList<>();
672
        for (PriceCircularItemModelNew priceCircularItemModel : priceCircular.getPriceCircularItemModelNews()) {
673
            List<Serializable> row = new ArrayList<>();
674
            row.add(priceCircularItemModel.getCatalogId());
675
            row.add(brand);
676
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelName());
677
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelNumber());
678
            //TODO: fix nlc
679
            //row.add(priceCircularItemModel.getNetPrice());
680
            rows.add(row);
681
        }
682
        return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
683
    }
30471 amit.gupta 684
 
31903 amit.gupta 685
    @RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
686
    public String selectPriceDropStatus(HttpServletRequest request,
687
                                        @RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
688
                                        Model model) throws Exception {
30250 amit.gupta 689
 
31903 amit.gupta 690
        model.addAttribute("selectedStatus", selectedStatus);
691
        return "pricedrop-status-change";
692
    }
30250 amit.gupta 693
 
23819 govind 694
}