Subversion Repositories SmartDukaan

Rev

Rev 34651 | Rev 34720 | 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 {
34657 aman.kumar 153
        if (endDate.isAfter(LocalDateTime.now().plusDays(1)) || startDate.isAfter(LocalDateTime.now().plusDays(1))) {
34651 aman.kumar 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
    @RequestMapping(value = "/pricedropByDate/download", method = RequestMethod.GET)
181
    public ResponseEntity<?> dowloadItems(HttpServletRequest request, @PathVariable(name = "tagId") @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate)
182
            throws Throwable {
183
        List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetweenSortByDate(startDate, endDate);
184
        Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
185
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
186
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
187
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
188
 
189
        List<List<?>> rows = new ArrayList<>();
190
        for (PriceDrop priceDrop : priceDrops) {
191
            rows.add(Arrays.asList(priceDrop.getId(), catalogDescription.get(priceDrop.getCatalogItemId()), priceDrop.getTp(), priceDrop.getOldDp(), priceDrop.getMop(),
34657 aman.kumar 192
                    priceDrop.getAmount(), priceDrop.getNewDp(), FormattingUtils.formatDate(priceDrop.getAffectedOn()), FormattingUtils.formatDate(priceDrop.getCreatedOn())
34651 aman.kumar 193
            ));
194
 
195
        }
196
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
197
                Arrays.asList("Drop Id", "Item Name", "TP", "DP", "Mop", "Price Drop",
198
                        "New DP", "Affected On", "Created On"),
199
                rows);
200
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Price Drop ");
201
        return responseEntity;
202
    }
203
 
31903 amit.gupta 204
    @RequestMapping(value = "/getClosedPricedropItemDescription", method = RequestMethod.GET)
205
    public String getClosedPricedropItemDescription(HttpServletRequest request, Model model) throws Throwable {
206
        List<PriceDrop> priceDrops = priceDropRepository.selectAllComplete();
207
        int processOn = 1;
23819 govind 208
 
31903 amit.gupta 209
        List<PriceDrop> completePriceDrops = priceDrops.stream().filter(x -> x.getCompleteTimestamp() != null)
210
                .collect(Collectors.toList());
23945 amit.gupta 211
 
31903 amit.gupta 212
        Set<Integer> catalogIds = completePriceDrops.stream().map(x -> x.getCatalogItemId())
213
                .collect(Collectors.toSet());
214
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
215
        LOGGER.info("catalogIds" + catalogIds);
23819 govind 216
 
31903 amit.gupta 217
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
218
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
219
        model.addAttribute("priceDrops", completePriceDrops);
220
        model.addAttribute("processOn", processOn);
221
        model.addAttribute("catalogDescription", catalogDescription);
222
        return "price-drop";
223
    }
23945 amit.gupta 224
 
31903 amit.gupta 225
    @RequestMapping(value = "/item-pricing/{itemId}", method = RequestMethod.GET)
226
    public String getItemPricing(HttpServletRequest request, Model model, @PathVariable int itemId) throws Throwable {
23819 govind 227
 
31903 amit.gupta 228
        TagListing tagListing;
229
        PriceDropModel pm = new PriceDropModel();
230
        try {
231
            tagListing = tagListingRepository.selectByItemId(itemId);
232
            if (tagListing != null) {
233
                pm.setMop(tagListing.getMop());
234
                pm.setDp(tagListing.getSellingPrice());
235
                pm.setMrp(tagListing.getMrp());
236
                List<VendorItemPricing> vips = vendorItemPricingRepository.selectAll(itemId);
237
                if (vips.size() > 0) {
238
                    VendorItemPricing vip = vips.get(0);
239
                    pm.setNlc(vip.getNlc());
240
                    pm.setTp(vip.getTp());
241
                } else {
242
                    throw new ProfitMandiBusinessException("Item Id", itemId, "Vendor item pricing does not exist");
243
                }
244
            }
245
        } catch (Exception e) {
246
            LOGGER.info("Chose item that doesn't exist");
247
        }
248
        model.addAttribute("response1", mvcResponseSender.createResponseString(pm));
249
        return "response";
250
    }
27071 amit.gupta 251
 
31903 amit.gupta 252
    @RequestMapping(value = "/item", method = RequestMethod.GET)
253
    public String getItemPricing(HttpServletRequest request, Model model, @RequestParam String query,
254
                                 @RequestParam boolean anyColor) throws Throwable {
255
        String query1 = query.toLowerCase();
24083 amit.gupta 256
 
31903 amit.gupta 257
        List<ItemDescriptionModel> partnersItemDescription = inventoryService
258
                .getAllPartnerItemStringDescription(anyColor).parallelStream()
259
                .filter(x -> x.getItemDescription().toLowerCase().matches(".*?" + query1 + ".*?"))
260
                .collect(Collectors.toList());
261
        LOGGER.info("partnersItemDescription" + partnersItemDescription);
23819 govind 262
 
31903 amit.gupta 263
        model.addAttribute("response1", mvcResponseSender.createResponseString(partnersItemDescription));
264
        return "response";
265
    }
23945 amit.gupta 266
 
31903 amit.gupta 267
    @RequestMapping(value = "/price-drop/imes/download")
268
    public ResponseEntity<ByteArrayResource> downloadPriceDropImeis(HttpServletRequest request,
269
                                                                    @RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws Exception {
270
        Item item = itemRepository.selectById(itemId);
33198 amit.gupta 271
        ByteArrayOutputStream baos = getByteArrayOutputStream(affectedDate, item.getCatalogItemId(), null, Optional.empty());
31903 amit.gupta 272
        final HttpHeaders headers = new HttpHeaders();
273
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
274
        headers.set("Content-disposition", "inline; filename=\"imei-" + item.getItemDescriptionNoColor() + ".csv\"");
275
        byte[] byteArray = baos.toByteArray();
276
        headers.setContentLength(byteArray.length);
277
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
278
    }
23819 govind 279
 
31903 amit.gupta 280
    @RequestMapping(value = "/price-drop/addPayout", method = RequestMethod.POST)
281
    public String updatePriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
282
                                  Model model) throws Exception {
283
        boolean response = false;
284
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
285
        if (priceDrop.getProcessTimestamp() == null) {
286
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
287
            priceDrop.setPriceDropIn(priceDropProcessModel.getPriceDropIn());
288
            // priceDrop.setProcessTimestamp(LocalDateTime.now());
289
            priceDropRepository.persist(priceDrop);
290
            response = true;
291
        }
292
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
293
        return "response";
294
    }
24083 amit.gupta 295
 
31903 amit.gupta 296
    @RequestMapping(value = "/priceDropImeis/{priceDropId}", method = RequestMethod.GET)
297
    public String priceDropStatus(HttpServletRequest request, @PathVariable int priceDropId, Model model)
298
            throws Exception {
29951 amit.gupta 299
 
31903 amit.gupta 300
        PriceDropImeisModel priceDropImeisModel = new PriceDropImeisModel();
23819 govind 301
 
31903 amit.gupta 302
        // This call is used to persit imeis to pricedrop imeis in case its not there.
303
        // This should be called while creating price drop.
304
        // priceDropService.priceDropStatus(priceDropId);
24083 amit.gupta 305
 
31903 amit.gupta 306
        List<String> pendingImeis = new ArrayList<>();
307
        List<String> approvedImeis = new ArrayList<>();
308
        List<String> rejectedImeis = new ArrayList<>();
309
        List<String> holdImeis = new ArrayList<>();
310
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
311
        for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
312
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.PENDING)) {
313
                pendingImeis.add(priceDropIMEI.getImei());
314
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)) {
315
                approvedImeis.add(priceDropIMEI.getImei());
316
            }
317
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.REJECTED)) {
318
                rejectedImeis.add(priceDropIMEI.getImei());
319
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
320
                holdImeis.add(priceDropIMEI.getImei());
24083 amit.gupta 321
 
31903 amit.gupta 322
            }
323
        }
324
        LOGGER.info("pendingImeis" + pendingImeis);
325
        LOGGER.info("approvedImeis" + approvedImeis);
326
        LOGGER.info("rejectedImeis" + rejectedImeis);
327
        LOGGER.info("priceDropImeis" + priceDropImeis);
23945 amit.gupta 328
 
31903 amit.gupta 329
        priceDropImeisModel.setPendingImeis(pendingImeis);
330
        priceDropImeisModel.setPriceDropId(priceDropId);
331
        priceDropImeisModel.setApprovedImeis(approvedImeis);
332
        priceDropImeisModel.setHoldImeis(holdImeis);
333
        priceDropImeisModel.setRejectedImeis(rejectedImeis);
334
        model.addAttribute("response1", mvcResponseSender.createResponseString(priceDropImeisModel));
335
        return "response";
336
    }
28102 tejbeer 337
 
31903 amit.gupta 338
    @RequestMapping(value = "/processPriceDrop", method = RequestMethod.POST)
339
    public String processPriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
340
                                   Model model) throws Exception {
341
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
342
        boolean response = false;
343
        if (priceDrop.getPartnerPayout() == 0) {
344
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
345
        }
346
        priceDrop.setProcessTimestamp(LocalDateTime.now());
347
        priceDropService.processPriceDrop(priceDrop.getId(), priceDropProcessModel.isActivatedOnly());
348
        response = true;
349
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
350
        return "response";
351
    }
28102 tejbeer 352
 
31903 amit.gupta 353
    @RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
354
    public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
355
            throws Exception {
356
        boolean response = false;
357
        priceDropModel.setAllColors(true);
358
        if (this.validatePriceDrop(priceDropModel)) {
359
            TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
360
            float oldDp = tagListing.getSellingPrice();
361
            float oldMop = tagListing.getMop();
362
            float oldTp = 0;
363
            float newDp = priceDropModel.getDp();
28102 tejbeer 364
 
31903 amit.gupta 365
            if (newDp != oldDp) {
366
                List<Item> allItems = null;
367
                Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
368
                if (priceDropModel.isAllColors()) {
369
                    allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
28102 tejbeer 370
 
31903 amit.gupta 371
                } else {
372
                    allItems = Arrays.asList(currentItem);
373
                }
374
                for (Item item : allItems) {
375
                    TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
376
                    if (itemTagListing == null)
377
                        continue;
378
                    itemTagListing.setSellingPrice(newDp);
379
                    itemTagListing.setMop(priceDropModel.getMop());
380
                    List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
381
                    for (VendorItemPricing vip : vipList) {
382
                        oldTp = vip.getNlc();
383
                        vip.setDp(newDp);
384
                        vip.setMop(priceDropModel.getMop());
385
                        //Lets not update NLC/TP as it has to be managed by Category Tea,
386
                        //vip.setNlc(priceDropModel.getTp());
387
                        //vip.setTp(priceDropModel.getTp());
388
                        vendorItemPricingRepository.persist(vip);
389
                    }
390
                    transactionService.updatePriceDrop(item.getId(), newDp);
391
                }
29926 amit.gupta 392
 
31903 amit.gupta 393
                // Add to itemPricing history
394
                ItemPricingHistory iph = new ItemPricingHistory();
395
                iph.setCatalogId(currentItem.getCatalogItemId());
396
                iph.setTp(priceDropModel.getTp());
397
                iph.setDp(priceDropModel.getDp());
398
                iph.setMop(priceDropModel.getMop());
399
                // TODO: changedBy
400
                iph.setChangedBy("me");
401
                iph.setCreateTimestamp(LocalDateTime.now());
402
                itemPricingHistoryRepository.persist(iph);
28136 tejbeer 403
 
31903 amit.gupta 404
                PriceDrop priceDrop = new PriceDrop();
405
                priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
406
                priceDrop.setTp(oldTp);
407
                priceDrop.setNlc(oldTp);
408
                priceDrop.setMop(oldMop);
409
                priceDrop.setOldDp(oldDp);
410
                priceDrop.setAmount(oldDp - newDp);
411
                priceDrop.setNewDp(newDp);
412
                priceDrop.setCreatedOn(LocalDateTime.now());
413
                priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
414
                priceDropRepository.persist(priceDrop);
415
                priceDropService.priceDropStatus(priceDrop.getId());
416
                response = true;
30471 amit.gupta 417
 
31903 amit.gupta 418
                this.sendPriceChangeNotification(priceDrop);
419
            } else {
420
                throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
421
                        "Price Drop Should be greater than 0");
422
            }
423
        }
424
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
425
        return "response";
426
    }
29654 tejbeer 427
 
31903 amit.gupta 428
    private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
429
        List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
430
        String title = "Price has been %s for %s";
24083 amit.gupta 431
 
28568 amit.gupta 432
 
31903 amit.gupta 433
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
434
        sendNotificationModel.setCampaignName("pricechange");
435
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
436
        sendNotificationModel.setTitle("");
437
        StringBuffer sb = new StringBuffer();
438
        String message = null;
439
        if (priceDrop.getDropAmount() > 0) {
440
            title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
441
            message = String.format("Price has been dropped from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(priceDrop.getDropAmount()),
442
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
443
        } else {
444
            title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
445
            message = String.format("Price has been increased from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(-priceDrop.getDropAmount()),
446
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
447
        }
448
        sendNotificationModel.setTitle(title);
449
        sendNotificationModel.setMessage(message);
450
        sendNotificationModel.setMessageType(MessageType.pricechange);
451
        notificationService.sendNotificationToAll(sendNotificationModel);
452
    }
28568 amit.gupta 453
 
31903 amit.gupta 454
    @RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
455
    public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
456
                                                        Model model) throws ProfitMandiBusinessException, Exception {
28568 amit.gupta 457
 
31903 amit.gupta 458
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
459
        Map<String, PriceDropIMEI> priceDropIMEIsMap = priceDropIMEIRepository.selectByPriceDropId(priceDropId).stream()
460
                .collect(Collectors.toMap(x -> x.getImei(), x -> x));
461
        LOGGER.info("PriceDropImeis {}, priceDropId {}", priceDropIMEIsMap, priceDropId);
462
        Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
463
        final HttpHeaders headers = new HttpHeaders();
464
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
465
        headers.set("Content-disposition",
466
                "inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
467
                        + FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
468
        ByteArrayOutputStream baos = null;
469
        if (priceDropIMEIsMap.size() == 0) {
470
            priceDropService.priceDropStatus(priceDrop.getId());
471
            baos = FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
472
                    "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
473
                    "Grn On", "Activation Timestamp", "Activation Added On"), new ArrayList<>());
474
        } else {
28568 amit.gupta 475
 
31903 amit.gupta 476
            LOGGER.info("In else block");
33198 amit.gupta 477
            baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(), priceDropIMEIsMap, Optional.of(priceDrop.getCreatedOn()));
31903 amit.gupta 478
        }
479
        byte[] byteArray = baos.toByteArray();
480
        headers.setContentLength(byteArray.length);
481
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
24083 amit.gupta 482
 
31903 amit.gupta 483
    }
24083 amit.gupta 484
 
31903 amit.gupta 485
    @RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
33470 amit.gupta 486
    public String updatePriceDropImeis(@RequestBody PriceDropImeisModel priceDropImeisModel,
487
                                       Model model) throws Exception {
32012 amit.gupta 488
        final PriceDropImeiStatus status;
28102 tejbeer 489
 
31903 amit.gupta 490
        switch (priceDropImeisModel.getUpdatedStatus()) {
491
            case "approved": {
492
                status = PriceDropImeiStatus.APPROVED;
493
                break;
494
            }
32012 amit.gupta 495
            case "pending": {
496
                status = PriceDropImeiStatus.PENDING;
31903 amit.gupta 497
                break;
498
            }
499
            case "rejected": {
500
                status = PriceDropImeiStatus.REJECTED;
501
                break;
502
            }
32012 amit.gupta 503
            case "hold": {
504
                status = PriceDropImeiStatus.HOLD;
505
                break;
506
            }
507
            default:
508
                throw new IllegalStateException("Unexpected value: " + priceDropImeisModel.getUpdatedStatus());
31903 amit.gupta 509
        }
24168 amit.gupta 510
 
31903 amit.gupta 511
        if (PriceDropImeiStatus.PENDING.equals(status)) {
32012 amit.gupta 512
            List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByStatuses(Arrays.asList(PriceDropImeiStatus.REJECTED, PriceDropImeiStatus.HOLD),
31903 amit.gupta 513
                    priceDropImeisModel.getPriceDropId());
514
            LOGGER.info("hello" + priceDropIMEIs);
32012 amit.gupta 515
            for (PriceDropIMEI priceDropIMEI : priceDropIMEIs) {
516
                if (priceDropIMEI.getStatus().equals(status) || !priceDropImeisModel.getUpdatedImeis().contains(priceDropIMEI.getImei())) {
517
                    continue;
31903 amit.gupta 518
                }
32012 amit.gupta 519
                priceDropIMEI.setStatus(PriceDropImeiStatus.PENDING);
31903 amit.gupta 520
            }
521
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
522
            return "response";
523
        }
23951 amit.gupta 524
 
32012 amit.gupta 525
        if (status.equals(PriceDropImeiStatus.APPROVED)) {
526
            priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
527
                    priceDropImeisModel.getUpdatedImeis());
528
        }
529
 
31903 amit.gupta 530
        List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
531
                .selectByPriceDropId(priceDropImeisModel.getPriceDropId());
532
        List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
533
                .filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
32012 amit.gupta 534
                .filter(x -> !x.getStatus().equals(status)).collect(Collectors.toList());
31903 amit.gupta 535
        for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
536
            if (status.equals(PriceDropImeiStatus.REJECTED)
537
                    && priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
538
                priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
539
                priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
540
                priceDropImei.setRejectTimestamp(LocalDateTime.now());
541
            } else if (status.equals(PriceDropImeiStatus.HOLD)) {
542
                if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
543
                    priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
544
                } else {
545
                    throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
546
                }
28568 amit.gupta 547
 
31903 amit.gupta 548
            }
28568 amit.gupta 549
 
31903 amit.gupta 550
        }
28568 amit.gupta 551
 
31903 amit.gupta 552
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
553
        return "response";
24083 amit.gupta 554
 
31903 amit.gupta 555
    }
24083 amit.gupta 556
 
31903 amit.gupta 557
    private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
33198 amit.gupta 558
                                                           Map<String, PriceDropIMEI> priceDropImeis, Optional<LocalDateTime> createdOn) throws Exception {
559
 
31903 amit.gupta 560
        List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
33198 amit.gupta 561
                .getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId, createdOn);
31903 amit.gupta 562
        List<List<?>> rows = new ArrayList<>();
563
        for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
564
            if (priceDropImeis == null) {
565
                rows.add(this.getRow(imeiDropSummaryModel, null));
566
            } else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
567
                rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
568
            }
569
        }
570
        return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
571
                "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
572
                "Grn On", "Activation Timestamp", "Activation Added On"), rows);
573
    }
24083 amit.gupta 574
 
31903 amit.gupta 575
    private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
576
                                                PriceDropIMEI priceDropIMEI) {
577
        List<Serializable> row = new ArrayList<>();
578
        row.add(imeiDropSummaryModel.getSerialNumber());
579
        row.add(imeiDropSummaryModel.getStoreName());
580
        row.add(imeiDropSummaryModel.getPartnerCode());
581
        row.add(imeiDropSummaryModel.getItemId());
582
        row.add(imeiDropSummaryModel.getBrand());
583
        row.add(imeiDropSummaryModel.getModelName());
584
        row.add(imeiDropSummaryModel.getModelNumber());
585
        row.add(imeiDropSummaryModel.getColor());
586
        if (priceDropIMEI != null) {
587
            row.add(priceDropIMEI.getStatus());
588
            row.add(priceDropIMEI.getRejectionReason());
589
        } else {
590
            row.add(PriceDropImeiStatus.PENDING);
591
            row.add("");
592
        }
593
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
594
        row.add(imeiDropSummaryModel.getVendorName());
595
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
596
        row.add(imeiDropSummaryModel.getActivationTimestamp());
597
        row.add(imeiDropSummaryModel.getActivationAddedOn());
598
        return row;
599
    }
23819 govind 600
 
31903 amit.gupta 601
    private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
602
        if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
603
            return true;
604
        }
605
        return false;
606
    }
23945 amit.gupta 607
 
32844 shampa 608
    @Autowired
609
    BrandsService brandsService;
33470 amit.gupta 610
 
31903 amit.gupta 611
    @RequestMapping(value = "/priceCircular")
612
    public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
613
        int fofoId = Utils.SYSTEM_PARTNER_ID;
32844 shampa 614
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
31903 amit.gupta 615
        model.addAttribute("brands", brands);
616
        model.addAttribute("isAdmin", true);
617
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 618
 
31903 amit.gupta 619
        return "partner-price-circular";
620
    }
28102 tejbeer 621
 
31903 amit.gupta 622
    @RequestMapping(value = "/partnerPriceCircular")
623
    public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
624
        int fofoId = Utils.SYSTEM_PARTNER_ID;
32844 shampa 625
        Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
626
        brands.addAll(brandsService.getBrandsToDisplay(6).stream().map(x -> (String) x.getName())
31903 amit.gupta 627
                .collect(Collectors.toSet()));
628
        model.addAttribute("brands", brands);
629
        model.addAttribute("isAdmin", false);
28102 tejbeer 630
 
31903 amit.gupta 631
        return "partner-price-circular";
632
    }
28102 tejbeer 633
 
31903 amit.gupta 634
    @RequestMapping(value = "/priceCircularByBrand")
635
    public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
636
            throws ProfitMandiBusinessException {
637
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
638
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
639
        } else {
640
            fofoId = loginDetails.getFofoId();
641
        }
32905 shampa 642
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
643
 
31903 amit.gupta 644
        //.minusDays(2)
34317 amit.gupta 645
        PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
646
        return this.getPriceCircularView(priceCircularModel, model, fs.getCode());
32331 amit.gupta 647
    }
648
 
34317 amit.gupta 649
    public String getPriceCircularView(PriceCircularModel priceCircularModel, Model model, String partnerCode) {
650
        List<String> allMarginsSet = new ArrayList<>(this.getSchemeHeaders(priceCircularModel));
651
        List<String> sellins = SchemeType.IN_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
652
        List<String> sellouts = SchemeType.OUT_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
653
        List<String> allMargins = new ArrayList<>();
654
        allMargins.addAll(sellins);
655
        allMargins.addAll(sellouts);
31903 amit.gupta 656
        LOGGER.info("Sellins - {}", sellins);
657
        LOGGER.info("Sellouts - {}", sellouts);
34317 amit.gupta 658
        model.addAttribute("priceCircularItemModels", priceCircularModel.getPriceCircularItemModelNews());
31903 amit.gupta 659
        model.addAttribute("allMargins", allMargins);
660
        model.addAttribute("sellins", sellins);
661
        model.addAttribute("sellouts", sellouts);
34317 amit.gupta 662
        model.addAttribute("offers", priceCircularModel.getOffers());
663
        model.addAttribute("upgradeOffer", priceCircularModel.isUpgradeOffer());
31903 amit.gupta 664
        model.addAttribute("mvcResponseSender", mvcResponseSender);
32905 shampa 665
        model.addAttribute("partnerCode", partnerCode);
32331 amit.gupta 666
        return "price-circular-table";
31903 amit.gupta 667
    }
29951 amit.gupta 668
 
31903 amit.gupta 669
    private Set<String> getSchemeHeaders(PriceCircularModel priceCircular) {
670
        Set<String> schemeHeaders = new HashSet<>();
671
        priceCircular.getPriceCircularItemModelNews().stream().forEach(priceCircularItemModelNew -> {
672
            Map<String, AmountModel> headerMap = new HashMap<>();
673
            priceCircularItemModelNew.setHeaderSchemeModelsMap(headerMap);
674
            priceCircularItemModelNew.getSchemeSummaryModels().stream().forEach(schemeSummaryModel -> {
675
                if (schemeSummaryModel == null) return;
34317 amit.gupta 676
                schemeSummaryModel.setHeader(schemeSummaryModel.getSchemeType().getValue());
31903 amit.gupta 677
                if (!headerMap.containsKey(schemeSummaryModel.getHeader())) {
678
                    headerMap.put(schemeSummaryModel.getHeader(), new AmountModel(schemeSummaryModel.getAmount(), schemeSummaryModel.getAmountType()));
679
                } else {
680
                    AmountModel model = headerMap.get(schemeSummaryModel.getHeader());
681
                    model.setAmount(model.getAmount() + schemeSummaryModel.getAmount());
682
                }
683
                schemeHeaders.add(schemeSummaryModel.getHeader());
684
            });
685
        });
28102 tejbeer 686
 
31903 amit.gupta 687
        LOGGER.info("Scheme headers - {}", schemeHeaders);
688
        return schemeHeaders;
689
    }
30250 amit.gupta 690
 
31903 amit.gupta 691
    //private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
692
    //private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
30471 amit.gupta 693
 
30562 amit.gupta 694
 
31903 amit.gupta 695
    @RequestMapping(value = "/downloadNlcByBrand")
696
    public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
697
                                                                @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
698
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
699
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
700
        } else {
701
            fofoId = loginDetails.getFofoId();
702
        }
703
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
704
        /*List<Integer> catalogIds = priceCircular.getPriceCircularItemModelNews().stream().limit(10).map(x->x.getCatalogId()).collect(Collectors.toList());
705
        priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());*/
706
        ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
707
        final HttpHeaders headers = new HttpHeaders();
708
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
709
        headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
710
        byte[] byteArray = baos.toByteArray();
711
        headers.setContentLength(byteArray.length);
712
        return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
713
    }
30471 amit.gupta 714
 
31903 amit.gupta 715
    private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
716
        List<List<?>> rows = new ArrayList<>();
717
        for (PriceCircularItemModelNew priceCircularItemModel : priceCircular.getPriceCircularItemModelNews()) {
718
            List<Serializable> row = new ArrayList<>();
719
            row.add(priceCircularItemModel.getCatalogId());
720
            row.add(brand);
721
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelName());
722
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelNumber());
723
            //TODO: fix nlc
724
            //row.add(priceCircularItemModel.getNetPrice());
725
            rows.add(row);
726
        }
727
        return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
728
    }
30471 amit.gupta 729
 
31903 amit.gupta 730
    @RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
731
    public String selectPriceDropStatus(HttpServletRequest request,
732
                                        @RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
733
                                        Model model) throws Exception {
30250 amit.gupta 734
 
31903 amit.gupta 735
        model.addAttribute("selectedStatus", selectedStatus);
736
        return "pricedrop-status-change";
737
    }
30250 amit.gupta 738
 
23819 govind 739
}