Subversion Repositories SmartDukaan

Rev

Rev 37604 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
32075 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
32900 amit.gupta 3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
32194 tejbeer 4
import com.spice.profitmandi.common.model.ItemDescriptionModel;
33183 shampa 5
import com.spice.profitmandi.common.util.FileUtil;
6
import com.spice.profitmandi.common.util.FormattingUtils;
32075 tejbeer 7
import com.spice.profitmandi.dao.entity.auth.AuthUser;
34047 tejus.loha 8
import com.spice.profitmandi.dao.entity.catalog.CategorisedCatalog;
32075 tejbeer 9
import com.spice.profitmandi.dao.entity.catalog.Item;
10
import com.spice.profitmandi.dao.entity.inventory.Vendor;
11
import com.spice.profitmandi.dao.entity.inventory.VendorCatalogPricing;
12
import com.spice.profitmandi.dao.entity.inventory.VendorCatalogPricingLog;
13
import com.spice.profitmandi.dao.entity.warehouse.Supplier;
14
import com.spice.profitmandi.dao.enumuration.inventory.VendorCatalogPricingStatus;
37604 amit 15
import com.spice.profitmandi.dao.model.InternalMovementAllocationModel;
32075 tejbeer 16
import com.spice.profitmandi.dao.model.VendorCatalogPricingModel;
32163 tejbeer 17
import com.spice.profitmandi.dao.model.VendorPriceCircularModel;
32075 tejbeer 18
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
34047 tejus.loha 19
import com.spice.profitmandi.dao.repository.catalog.CategorisedCatalogRepository;
32075 tejbeer 20
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
21
import com.spice.profitmandi.dao.repository.inventory.VendorCatalogPricingLogRepository;
22
import com.spice.profitmandi.dao.repository.inventory.VendorCatalogPricingRepository;
23
import com.spice.profitmandi.dao.repository.inventory.VendorRepository;
33183 shampa 24
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
32075 tejbeer 25
import com.spice.profitmandi.dao.repository.warehouse.SupplierRepository;
33183 shampa 26
import com.spice.profitmandi.service.authentication.RoleManager;
32075 tejbeer 27
import com.spice.profitmandi.service.inventory.VendorCatalogPricingService;
33183 shampa 28
import com.spice.profitmandi.service.order.OrderService;
37604 amit 29
import com.spice.profitmandi.service.warehouse.InternalMovementPricingService;
32194 tejbeer 30
import com.spice.profitmandi.service.warehouse.WarehouseService;
32075 tejbeer 31
import com.spice.profitmandi.web.model.LoginDetails;
32
import com.spice.profitmandi.web.util.CookiesProcessor;
33
import com.spice.profitmandi.web.util.MVCResponseSender;
32383 amit.gupta 34
import org.apache.logging.log4j.LogManager;
35
import org.apache.logging.log4j.Logger;
36
import org.springframework.beans.factory.annotation.Autowired;
33465 ranu 37
import org.springframework.core.io.ClassPathResource;
38
import org.springframework.core.io.InputStreamResource;
39
import org.springframework.http.HttpHeaders;
40
import org.springframework.http.MediaType;
33183 shampa 41
import org.springframework.http.ResponseEntity;
32383 amit.gupta 42
import org.springframework.stereotype.Controller;
43
import org.springframework.transaction.annotation.Transactional;
44
import org.springframework.ui.Model;
33465 ranu 45
import org.springframework.web.bind.annotation.*;
46
import org.springframework.web.multipart.MultipartFile;
32075 tejbeer 47
 
36464 amit 48
import org.apache.poi.ss.usermodel.CellStyle;
49
import org.apache.poi.ss.usermodel.Font;
50
import org.apache.poi.xssf.usermodel.XSSFRow;
51
import org.apache.poi.xssf.usermodel.XSSFSheet;
52
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
53
 
33465 ranu 54
import javax.mail.MessagingException;
32383 amit.gupta 55
import javax.servlet.http.HttpServletRequest;
36464 amit 56
import java.io.ByteArrayInputStream;
57
import java.io.ByteArrayOutputStream;
33465 ranu 58
import java.io.IOException;
32383 amit.gupta 59
import java.time.LocalDate;
60
import java.time.LocalDateTime;
61
import java.util.*;
62
import java.util.stream.Collectors;
63
 
32075 tejbeer 64
@Controller
65
@Transactional(rollbackFor = Throwable.class)
66
public class VendorController {
67
 
68
 
69
    @Autowired
70
    VendorRepository vendorRepository;
71
 
72
    @Autowired
73
    private CookiesProcessor cookiesProcessor;
74
 
75
    @Autowired
33183 shampa 76
    private RoleManager roleManager;
77
 
78
    @Autowired
32075 tejbeer 79
    private AuthRepository authRepository;
80
 
81
    @Autowired
33183 shampa 82
    private OrderRepository orderRepository;
83
 
84
    @Autowired
85
    private OrderService orderService;
86
 
87
    @Autowired
32075 tejbeer 88
    private VendorCatalogPricingService vendorCatalogPricingService;
89
 
90
    @Autowired
91
    private VendorCatalogPricingLogRepository vendorCatalogPricingLogRepository;
92
 
93
    @Autowired
94
    private VendorCatalogPricingRepository vendorCatalogPricingRepository;
95
 
96
 
97
    @Autowired
98
    private MVCResponseSender mvcResponseSender;
99
 
100
    @Autowired
101
    private ItemRepository itemRepository;
102
 
103
    @Autowired
104
    private SupplierRepository supplierRepository;
105
 
32194 tejbeer 106
    @Autowired
107
    private WarehouseService warehouseService;
108
 
34047 tejus.loha 109
    @Autowired
37604 amit 110
    private InternalMovementPricingService internalMovementPricingService;
111
 
112
    @Autowired
34047 tejus.loha 113
    CategorisedCatalogRepository categorisedCatalogRepository;
114
 
32075 tejbeer 115
    private static final Logger LOGGER = LogManager.getLogger(VendorController.class);
116
 
117
 
118
    @RequestMapping(value = "/vendorCatalogPricing", method = RequestMethod.GET)
34047 tejus.loha 119
    public String vendorCatalogPricing() throws Exception {
32075 tejbeer 120
        return "vendor-catalog-pricing";
121
    }
122
 
123
 
124
    @RequestMapping(value = "/getVendorCatalogPricingByModel", method = RequestMethod.GET)
34047 tejus.loha 125
    public String getVendorCatalogPricingByModel(@RequestParam int catalogId, Model model) throws Exception {
32075 tejbeer 126
 
127
        List<Integer> vendorIds = new ArrayList<>();
128
        Map<Integer, VendorCatalogPricing> vendorCatalogPricingMap = new HashMap<>();
129
        Map<Integer, VendorCatalogPricingLog> vendorCatalogPricingLogMap = new HashMap<>();
130
        List<VendorCatalogPricing> vendorCatalogPricing = vendorCatalogPricingRepository.selectByCatalogId(catalogId);
131
        if (!vendorCatalogPricing.isEmpty()) {
132
            vendorIds.addAll(vendorCatalogPricing.stream().distinct().map(x -> x.getVendorId()).collect(Collectors.toList()));
133
            vendorCatalogPricingMap = vendorCatalogPricing.stream().collect(Collectors.toMap(x -> x.getVendorId(), x -> x));
134
        }
135
 
136
        List<VendorCatalogPricingLog> vendorCatalogPricingLog = vendorCatalogPricingLogRepository.selectByCatalogId(catalogId, VendorCatalogPricingStatus.PENDING);
137
        if (!vendorCatalogPricingLog.isEmpty()) {
138
            vendorIds.addAll(vendorCatalogPricingLog.stream().distinct().map(x -> x.getVendorId()).collect(Collectors.toList()));
139
            vendorCatalogPricingLogMap = vendorCatalogPricingLog.stream().filter(x -> x.getStatus().equals(VendorCatalogPricingStatus.PENDING)).collect(Collectors.toMap(x -> x.getVendorId(), x -> x));
140
        }
141
        LOGGER.info("VendorIds {}", vendorIds);
142
        List<Supplier> suppliers = new ArrayList<Supplier>();
143
        if (!vendorIds.isEmpty()) {
144
            suppliers.addAll(supplierRepository.selectBySupplierIds(vendorIds));
145
        }
146
        LOGGER.info("suppliers {}", suppliers);
147
 
148
        model.addAttribute("suppliers", suppliers);
149
        model.addAttribute("vendorCatalogPricingMap", vendorCatalogPricingMap);
150
        model.addAttribute("vendorCatalogPricingLogMap", vendorCatalogPricingLogMap);
151
 
152
        model.addAttribute("catalogId", catalogId);
153
 
154
 
155
        return "vendor-catalog-pricing-view";
156
    }
157
 
158
 
159
    @RequestMapping(value = "/vendors", method = RequestMethod.GET)
34047 tejus.loha 160
    public String getVendor(Model model, @RequestParam String query) throws Throwable {
32398 amit.gupta 161
        List<Supplier> vendors = supplierRepository.selectAll().stream().filter(x -> x.getName().toLowerCase().matches(".*?" + query.toLowerCase() + ".*?"))
162
                .filter(x -> x.isStatus()).collect(Collectors.toList());
32075 tejbeer 163
        model.addAttribute("response1", mvcResponseSender.createResponseString(vendors));
164
        return "response";
165
    }
166
 
167
 
168
    @RequestMapping(value = "/createVendorCatalogPricing", method = RequestMethod.POST)
169
    public String createVendorCatalogPricing(HttpServletRequest request, @RequestBody VendorCatalogPricingModel vendorCatalogPricingModel, Model model) throws Exception {
170
 
171
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
172
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
173
        vendorCatalogPricingModel.setAuthId(authUser.getId());
174
 
175
        LOGGER.info("vendorCatalogPricingModel {}", vendorCatalogPricingModel);
176
 
177
        vendorCatalogPricingService.createVendorCatalogPricingLog(vendorCatalogPricingModel);
178
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
179
        return "response";
180
 
181
    }
182
 
33465 ranu 183
    @RequestMapping(value = "/createBulkPricing")
34047 tejus.loha 184
    public String createBulkPricing() throws ProfitMandiBusinessException, MessagingException, IOException {
33465 ranu 185
        return "bulk-vendor-pricing";
186
    }
32075 tejbeer 187
 
33465 ranu 188
    @PostMapping(value = "/bulkVendorCatalogPricing/upload")
189
    public String uploadCatalog(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
190
            throws Exception {
191
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
192
        int authId = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId()).getId();
193
        LOGGER.info("authId - {}", authId);
194
        vendorCatalogPricingService.parseBulkVendorCatalogPricing(file, authId);
195
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
196
        return "response";
197
    }
198
 
37133 amit 199
    @PostMapping(value = "/bulkVendorCatalogPricing/verify")
200
    public String bulkVerifyVendorCatalogPricing(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
201
            throws Exception {
202
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
203
        int authId = authRepository.selectByEmailOrMobile(loginDetails.getEmailId()).getId();
204
        LOGGER.info("bulk pricing approval by authId - {}", authId);
205
        vendorCatalogPricingService.approveBulkVendorCatalogPricing(file, authId);
206
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
207
        return "response";
208
    }
209
 
33465 ranu 210
    @GetMapping("/bulkVendorCatalogPricing/downloadReferenceFile")
33467 ranu 211
    public ResponseEntity<?> downloadReferenceFile() throws IOException {
33465 ranu 212
        ClassPathResource dummyFile = new ClassPathResource("vendor-catalog-pricing-file.xlsx"); // Make sure the file is in the resources folder
213
        return ResponseEntity.ok()
214
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=dummy-file.xlsx")
215
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
216
                .body(new InputStreamResource(dummyFile.getInputStream()));
217
    }
218
 
219
 
32075 tejbeer 220
    @RequestMapping(value = "/vendorCatalogPricingRequests", method = RequestMethod.GET)
34047 tejus.loha 221
    public String vendorCatalogPricingRequests(Model model) throws Exception {
32075 tejbeer 222
        List<VendorCatalogPricingLog> vendorCatalogPricingRequests = vendorCatalogPricingLogRepository.selectByStatus(VendorCatalogPricingStatus.PENDING);
223
        Map<Integer, AuthUser> authUserMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
224
        model.addAttribute("vendorCatalogPricingRequests", vendorCatalogPricingRequests);
225
        if (!vendorCatalogPricingRequests.isEmpty()) {
226
            Set<Integer> catalogIds = vendorCatalogPricingRequests.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
227
            List<Integer> vendorIds = vendorCatalogPricingRequests.stream().map(x -> x.getVendorId()).collect(Collectors.toList());
228
 
229
 
230
            Map<Integer, List<Item>> itemMap = itemRepository.selectAllByCatalogIds(catalogIds).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
231
            model.addAttribute("itemMap", itemMap);
232
        }
233
        Map<Integer, Vendor> vendorMap = vendorRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
234
        model.addAttribute("authMap", authUserMap);
235
        model.addAttribute("vendorMap", vendorMap);
236
        model.addAttribute("vendorPricingStatus", VendorCatalogPricingStatus.values());
237
 
238
        return "vendor-catalog-pricing-request";
239
    }
240
 
33750 ranu 241
    @RequestMapping(value = "/vendorCatalogPricingPendingRequests", method = RequestMethod.GET)
34047 tejus.loha 242
    public String vendorCatalogPricingPendingRequests() throws Exception {
33750 ranu 243
        return "vendor-catalog-pricing-pending-request";
244
    }
245
 
246
    @RequestMapping(value = "/datewiseVendorCatalogPricingPendingRequests", method = RequestMethod.GET)
34047 tejus.loha 247
    public String datewiseVendorCatalogPricingPendingRequests(@RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model) throws Exception {
33750 ranu 248
        List<VendorCatalogPricingLog> vendorCatalogPricingRequests = vendorCatalogPricingLogRepository.selectByDate(startDate, endDate);
249
        Map<Integer, AuthUser> authUserMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
250
        LOGGER.info("vendorCatalogPricingRequests {}", vendorCatalogPricingRequests);
251
        model.addAttribute("vendorCatalogPricingRequests", vendorCatalogPricingRequests);
252
        if (!vendorCatalogPricingRequests.isEmpty()) {
253
            Set<Integer> catalogIds = vendorCatalogPricingRequests.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
254
            Map<Integer, List<Item>> itemMap = itemRepository.selectAllByCatalogIds(catalogIds).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
255
            model.addAttribute("itemMap", itemMap);
256
        }
257
        Map<Integer, Vendor> vendorMap = vendorRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
258
        model.addAttribute("authMap", authUserMap);
259
        model.addAttribute("vendorMap", vendorMap);
260
        model.addAttribute("vendorPricingStatus", VendorCatalogPricingStatus.values());
261
 
262
        return "vendor-catalog-pricing-pending-request-table";
263
    }
264
 
32075 tejbeer 265
    @RequestMapping(value = "/verifyVendorCatalogPricingRequest", method = RequestMethod.POST)
266
    public String verifyVendorCatalogPricingRequest(HttpServletRequest request, @RequestParam int id, @RequestParam VendorCatalogPricingStatus status, Model model) throws Exception {
32086 tejbeer 267
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
268
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
32075 tejbeer 269
 
270
        VendorCatalogPricingLog vendorCatalogPricingLog = vendorCatalogPricingLogRepository.selectById(id);
32298 tejbeer 271
 
272
        if (status.equals(VendorCatalogPricingStatus.APPROVED)) {
37133 amit 273
            vendorCatalogPricingService.approveVendorCatalogPricingLog(vendorCatalogPricingLog, authUser.getId());
274
        } else {
275
            vendorCatalogPricingLog.setStatus(status);
276
            vendorCatalogPricingLog.setUpdatedTimestamp(LocalDateTime.now());
32298 tejbeer 277
        }
32075 tejbeer 278
 
279
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
280
        return "response";
281
    }
282
 
283
 
284
    @RequestMapping(value = "/vendorPriceCircular", method = RequestMethod.GET)
34047 tejus.loha 285
    public String vendorPriceCircular() throws Exception {
32075 tejbeer 286
        return "vendor-price-circular";
287
    }
288
 
289
 
290
    @RequestMapping(value = "/getVendorPriceCircular", method = RequestMethod.GET)
34047 tejus.loha 291
    public String getVendorPriceCircular(@RequestParam(defaultValue = "0") int vendorId, @RequestParam LocalDate effectedDate, Model model) throws Exception {
32075 tejbeer 292
 
32485 amit.gupta 293
        List<VendorPriceCircularModel> vendorCatalogPricings = vendorCatalogPricingLogRepository.getVendorPricesOnDate(vendorId, effectedDate);
33183 shampa 294
        Map<Integer, Supplier> supplierMap = supplierRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
32075 tejbeer 295
        if (!vendorCatalogPricings.isEmpty()) {
296
            Set<Integer> catalogIds = vendorCatalogPricings.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
297
            Map<Integer, List<Item>> itemMap = itemRepository.selectAllByCatalogIds(catalogIds).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
298
            model.addAttribute("itemMap", itemMap);
299
        }
300
 
301
        model.addAttribute("vendorCatalogPricings", vendorCatalogPricings);
33183 shampa 302
        model.addAttribute("suppliers", supplierMap);
32075 tejbeer 303
        return "vendor-price-circular-view";
304
 
305
    }
34047 tejus.loha 306
 
33183 shampa 307
    @RequestMapping(value = "/downloadPriceCircularReport", method = RequestMethod.GET)
34047 tejus.loha 308
    public ResponseEntity<?> getSelectDownloadPriceCircularReport(@RequestParam(name = "startDate") LocalDate startDate) throws Exception {
32145 tejbeer 309
 
33183 shampa 310
        List<VendorPriceCircularModel> vendorCatalogPricings = vendorCatalogPricingLogRepository.getVendorPricesOnDate(0, startDate);
311
        Map<Integer, Supplier> supplierMap = supplierRepository.selectAll().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
312
        Map<Integer, List<Item>> itemMap = new HashMap<>();
313
        List<List<?>> rows = new ArrayList<>();
314
        if (!vendorCatalogPricings.isEmpty()) {
315
            Set<Integer> catalogIds = vendorCatalogPricings.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
316
            itemMap = itemRepository.selectAllByCatalogIds(catalogIds).stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
317
        }
318
 
34047 tejus.loha 319
        for (VendorPriceCircularModel vcp : vendorCatalogPricings) {
36468 amit 320
            Supplier supplier = supplierMap.get(vcp.getVendorId());
321
            List<Item> items = itemMap.get(vcp.getCatalogId());
322
            if (supplier == null || supplier.isInternal() || items == null || items.isEmpty()) {
323
                continue;
324
            }
325
            rows.add(Arrays.asList(vcp.getCatalogId(), supplier.getName(), items.get(0).getItemDescriptionNoColor(), vcp.getTransferPrice(), vcp.getDealerPrice(), vcp.getMop(),
33183 shampa 326
                    FormattingUtils.formatDate(vcp.getEffectedOn())));
327
        }
328
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
34047 tejus.loha 329
                .getCSVByteStream(Arrays.asList("Catalog Id", "Vendor Name", "Model name", "TP", "DP", "MOP",
33183 shampa 330
                        "Effected On"), rows);
331
 
332
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "price circular report");
333
 
334
        return responseEntity;
335
 
336
    }
337
 
34047 tejus.loha 338
 
32145 tejbeer 339
    @RequestMapping(value = "/getPricing", method = RequestMethod.GET)
32488 amit.gupta 340
    public String getPricing(HttpServletRequest request, @RequestParam int vendorId, @RequestParam int itemId, @RequestParam LocalDate onDate, Model model) throws Exception {
34057 tejus.loha 341
        List<Integer> checkRequiredCategoryId = Arrays.asList(10006);
342
        List<String> checkRequiredCategoryGroup = Arrays.asList("Handset");
32901 amit.gupta 343
        Item item = itemRepository.selectById(itemId);
34050 tejus.loha 344
        List<String> brandsIgnoreToCheckCategory = Arrays.asList("Dummy", "Live Demo");
345
        if (!brandsIgnoreToCheckCategory.contains(item.getBrand())) {
346
            if (checkRequiredCategoryId.contains(item.getCategoryId()) || checkRequiredCategoryGroup.contains(item.getProductGroup())) {
347
                CategorisedCatalog categorisedCatalog = categorisedCatalogRepository.getCurrentCatalogMovement(item.getCatalogItemId());
348
                if (categorisedCatalog == null || categorisedCatalog.getStatus().getValue().isEmpty()) {
349
                    model.addAttribute("response1", mvcResponseSender.createResponseString(false));
350
                    return "response";
351
                }
34047 tejus.loha 352
            }
353
        }
37604 amit 354
        Supplier vendor = supplierRepository.selectById(vendorId);
355
        VendorPriceCircularModel vendorPriceCircularModel = vendor != null && vendor.isInternal()
356
                ? this.internalMovementPrice(vendor, item)
357
                : vendorCatalogPricingLogRepository.getVendorPriceOnDate(vendorId, item.getCatalogItemId(), onDate);
32488 amit.gupta 358
        LOGGER.info("vendorCatalogPricing {}", vendorPriceCircularModel);
359
        model.addAttribute("response1", mvcResponseSender.createResponseString(vendorPriceCircularModel));
32145 tejbeer 360
        return "response";
361
    }
32194 tejbeer 362
 
37604 amit 363
    /**
364
     * Price an item moving out of one of our own warehouses: it keeps the price of the vendor it was
365
     * originally bought from, so the sending warehouse's own circular is not consulted.
366
     *
37697 amit 367
     * <p>Answers with the price the oldest stock moves at, together with how many units this order can take and
368
     * what is holding the rest, so the quantity can be chosen correctly on screen rather than discovered on submit.
369
     * External vendors are untouched by this and still answer with a plain catalog price.
37604 amit 370
     */
371
    private VendorPriceCircularModel internalMovementPrice(Supplier vendor, Item item)
372
            throws ProfitMandiBusinessException {
37697 amit 373
        return internalMovementPricingService.describeAvailability(vendor, item);
32900 amit.gupta 374
    }
375
 
32194 tejbeer 376
    @RequestMapping(value = "/vendorItem", method = RequestMethod.GET)
34047 tejus.loha 377
    public String getItemPricing(Model model, @RequestParam int vendorId, @RequestParam String query) throws Exception {
32194 tejbeer 378
        String query1 = query.toLowerCase();
32903 amit.gupta 379
        LOGGER.info("Vendor Id - {}", vendorId);
37072 amit 380
        List<ItemDescriptionModel> partnersItemDescription = warehouseService.getAllPartnerItemStringDescription(vendorId).stream().filter(x -> x.getItemDescription().toLowerCase().contains(query1)).collect(Collectors.toList());
32194 tejbeer 381
        LOGGER.info("partnersItemDescription" + partnersItemDescription);
382
 
383
        model.addAttribute("response1", mvcResponseSender.createResponseString(partnersItemDescription));
384
        return "response";
385
    }
36464 amit 386
 
387
    @RequestMapping(value = "/downloadVendorPricingChangesReport", method = RequestMethod.GET)
388
    public ResponseEntity<?> downloadVendorPricingChangesReport(
389
            @RequestParam(name = "startDate") LocalDate startDate,
390
            @RequestParam(name = "endDate") LocalDate endDate) throws Exception {
391
 
392
        Map<Integer, Supplier> supplierMap = supplierRepository.selectAll().stream()
393
                .filter(s -> s.isStatus() && !s.isInternal())
394
                .collect(Collectors.toMap(Supplier::getId, s -> s));
395
 
396
        List<VendorPriceCircularModel> allBaseline = vendorCatalogPricingLogRepository.getVendorPricesOnDate(0, startDate);
397
        Map<Integer, List<VendorPriceCircularModel>> baselineByVendor = allBaseline.stream()
398
                .filter(p -> supplierMap.containsKey(p.getVendorId()))
399
                .collect(Collectors.groupingBy(VendorPriceCircularModel::getVendorId));
400
 
401
        List<VendorPriceCircularModel> allChanges = vendorCatalogPricingLogRepository.selectApprovedInDateRange(startDate, endDate);
402
        Map<Integer, List<VendorPriceCircularModel>> changesByVendor = allChanges.stream()
403
                .collect(Collectors.groupingBy(VendorPriceCircularModel::getVendorId));
404
 
405
        Set<Integer> allCatalogIds = new HashSet<>();
406
        allBaseline.stream().filter(p -> supplierMap.containsKey(p.getVendorId())).forEach(p -> allCatalogIds.add(p.getCatalogId()));
407
        allChanges.forEach(p -> allCatalogIds.add(p.getCatalogId()));
408
 
409
        Map<Integer, List<Item>> itemMap = new HashMap<>();
410
        if (!allCatalogIds.isEmpty()) {
411
            itemMap = itemRepository.selectAllByCatalogIds(allCatalogIds).stream()
412
                    .collect(Collectors.groupingBy(Item::getCatalogItemId));
413
        }
414
 
415
        ByteArrayOutputStream bos = buildVendorPricingChangesExcel(supplierMap, baselineByVendor, changesByVendor, itemMap);
416
 
417
        HttpHeaders headers = new HttpHeaders();
418
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
419
        headers.set("Content-disposition", "attachment; filename=vendor-pricing-changes-" + startDate + "-to-" + endDate + ".xlsx");
420
        headers.setContentLength(bos.toByteArray().length);
421
 
422
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(bos.toByteArray()));
423
        return new ResponseEntity<>(resource, headers, org.springframework.http.HttpStatus.OK);
424
    }
425
 
426
    private ByteArrayOutputStream buildVendorPricingChangesExcel(
427
            Map<Integer, Supplier> supplierMap,
428
            Map<Integer, List<VendorPriceCircularModel>> baselineByVendor,
429
            Map<Integer, List<VendorPriceCircularModel>> changesByVendor,
430
            Map<Integer, List<Item>> itemMap) throws Exception {
431
 
432
        XSSFWorkbook workbook = new XSSFWorkbook();
433
        XSSFSheet sheet = workbook.createSheet("Pricing Changes");
434
 
435
        CellStyle headerStyle = workbook.createCellStyle();
436
        Font boldFont = workbook.createFont();
437
        boldFont.setBold(true);
438
        headerStyle.setFont(boldFont);
439
 
440
        int rowNum = 0;
441
 
442
        XSSFRow colRow = sheet.createRow(rowNum++);
443
        String[] columns = {"Vendor", "Effective Date", "Model", "Catalog Id", "TP", "DP", "MOP"};
444
        for (int i = 0; i < columns.length; i++) {
445
            colRow.createCell(i).setCellValue(columns[i]);
446
            colRow.getCell(i).setCellStyle(headerStyle);
447
        }
448
 
449
        List<Map.Entry<Integer, Supplier>> sortedVendors = supplierMap.entrySet().stream()
450
                .sorted(Comparator.comparing(e -> e.getValue().getName()))
451
                .collect(Collectors.toList());
452
 
453
        for (Map.Entry<Integer, Supplier> vendorEntry : sortedVendors) {
454
            int vendorId = vendorEntry.getKey();
455
            String vendorName = vendorEntry.getValue().getName();
456
 
457
            List<VendorPriceCircularModel> baseline = baselineByVendor.getOrDefault(vendorId, Collections.emptyList());
458
            List<VendorPriceCircularModel> changes = changesByVendor.getOrDefault(vendorId, Collections.emptyList());
459
 
460
            if (baseline.isEmpty() && changes.isEmpty()) {
461
                continue;
462
            }
463
 
464
            Map<Integer, Float> tpTracker = new HashMap<>();
465
 
466
            for (VendorPriceCircularModel bp : baseline) {
467
                XSSFRow dataRow = sheet.createRow(rowNum++);
468
                dataRow.createCell(0).setCellValue(vendorName);
469
                dataRow.createCell(1).setCellValue(FormattingUtils.formatDate(bp.getEffectedOn()));
470
                dataRow.createCell(2).setCellValue(getModelName(itemMap, bp.getCatalogId()));
471
                dataRow.createCell(3).setCellValue(bp.getCatalogId());
472
                dataRow.createCell(4).setCellValue(bp.getTransferPrice());
473
                dataRow.createCell(5).setCellValue(bp.getDealerPrice());
474
                dataRow.createCell(6).setCellValue(bp.getMop());
475
                tpTracker.put(bp.getCatalogId(), bp.getTransferPrice());
476
            }
477
 
478
            for (VendorPriceCircularModel cp : changes) {
479
                Float lastTp = tpTracker.get(cp.getCatalogId());
480
                if (lastTp == null || Float.compare(lastTp, cp.getTransferPrice()) != 0) {
481
                    XSSFRow dataRow = sheet.createRow(rowNum++);
482
                    dataRow.createCell(0).setCellValue(vendorName);
483
                    dataRow.createCell(1).setCellValue(FormattingUtils.formatDate(cp.getEffectedOn()));
484
                    dataRow.createCell(2).setCellValue(getModelName(itemMap, cp.getCatalogId()));
485
                    dataRow.createCell(3).setCellValue(cp.getCatalogId());
486
                    dataRow.createCell(4).setCellValue(cp.getTransferPrice());
487
                    dataRow.createCell(5).setCellValue(cp.getDealerPrice());
488
                    dataRow.createCell(6).setCellValue(cp.getMop());
489
                    tpTracker.put(cp.getCatalogId(), cp.getTransferPrice());
490
                }
491
            }
492
        }
493
 
494
        for (int i = 0; i < 7; i++) {
495
            sheet.autoSizeColumn(i);
496
        }
497
 
498
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
499
        workbook.write(bos);
500
        workbook.close();
501
        return bos;
502
    }
503
 
504
    private String getModelName(Map<Integer, List<Item>> itemMap, int catalogId) {
505
        List<Item> items = itemMap.get(catalogId);
506
        if (items != null && !items.isEmpty()) {
507
            return items.get(0).getItemDescriptionNoColor();
508
        }
509
        return "Unknown (" + catalogId + ")";
510
    }
32075 tejbeer 511
}