Subversion Repositories SmartDukaan

Rev

Rev 34317 | Rev 34657 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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