Subversion Repositories SmartDukaan

Rev

Rev 37133 | Go to most recent revision | 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
     *
367
     * <p>Answers for a single unit, which is the price the oldest stock moves at. If a larger quantity is
368
     * then entered and it would run past that vendor's stock into another's, creating the order says so and
369
     * names how many can move at this price - the quantity is not known yet at this point.
370
     */
371
    private VendorPriceCircularModel internalMovementPrice(Supplier vendor, Item item)
372
            throws ProfitMandiBusinessException {
373
        InternalMovementAllocationModel price = internalMovementPricingService.resolvePrice(vendor, item.getId(), 1);
374
        return new VendorPriceCircularModel(0, vendor.getId(), item.getCatalogItemId(), price.getTransferPrice(),
375
                price.getDealerPrice(), price.getMop(), LocalDate.now(),
376
                VendorCatalogPricingStatus.APPROVED.name());
32900 amit.gupta 377
    }
378
 
32194 tejbeer 379
    @RequestMapping(value = "/vendorItem", method = RequestMethod.GET)
34047 tejus.loha 380
    public String getItemPricing(Model model, @RequestParam int vendorId, @RequestParam String query) throws Exception {
32194 tejbeer 381
        String query1 = query.toLowerCase();
32903 amit.gupta 382
        LOGGER.info("Vendor Id - {}", vendorId);
37072 amit 383
        List<ItemDescriptionModel> partnersItemDescription = warehouseService.getAllPartnerItemStringDescription(vendorId).stream().filter(x -> x.getItemDescription().toLowerCase().contains(query1)).collect(Collectors.toList());
32194 tejbeer 384
        LOGGER.info("partnersItemDescription" + partnersItemDescription);
385
 
386
        model.addAttribute("response1", mvcResponseSender.createResponseString(partnersItemDescription));
387
        return "response";
388
    }
36464 amit 389
 
390
    @RequestMapping(value = "/downloadVendorPricingChangesReport", method = RequestMethod.GET)
391
    public ResponseEntity<?> downloadVendorPricingChangesReport(
392
            @RequestParam(name = "startDate") LocalDate startDate,
393
            @RequestParam(name = "endDate") LocalDate endDate) throws Exception {
394
 
395
        Map<Integer, Supplier> supplierMap = supplierRepository.selectAll().stream()
396
                .filter(s -> s.isStatus() && !s.isInternal())
397
                .collect(Collectors.toMap(Supplier::getId, s -> s));
398
 
399
        List<VendorPriceCircularModel> allBaseline = vendorCatalogPricingLogRepository.getVendorPricesOnDate(0, startDate);
400
        Map<Integer, List<VendorPriceCircularModel>> baselineByVendor = allBaseline.stream()
401
                .filter(p -> supplierMap.containsKey(p.getVendorId()))
402
                .collect(Collectors.groupingBy(VendorPriceCircularModel::getVendorId));
403
 
404
        List<VendorPriceCircularModel> allChanges = vendorCatalogPricingLogRepository.selectApprovedInDateRange(startDate, endDate);
405
        Map<Integer, List<VendorPriceCircularModel>> changesByVendor = allChanges.stream()
406
                .collect(Collectors.groupingBy(VendorPriceCircularModel::getVendorId));
407
 
408
        Set<Integer> allCatalogIds = new HashSet<>();
409
        allBaseline.stream().filter(p -> supplierMap.containsKey(p.getVendorId())).forEach(p -> allCatalogIds.add(p.getCatalogId()));
410
        allChanges.forEach(p -> allCatalogIds.add(p.getCatalogId()));
411
 
412
        Map<Integer, List<Item>> itemMap = new HashMap<>();
413
        if (!allCatalogIds.isEmpty()) {
414
            itemMap = itemRepository.selectAllByCatalogIds(allCatalogIds).stream()
415
                    .collect(Collectors.groupingBy(Item::getCatalogItemId));
416
        }
417
 
418
        ByteArrayOutputStream bos = buildVendorPricingChangesExcel(supplierMap, baselineByVendor, changesByVendor, itemMap);
419
 
420
        HttpHeaders headers = new HttpHeaders();
421
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
422
        headers.set("Content-disposition", "attachment; filename=vendor-pricing-changes-" + startDate + "-to-" + endDate + ".xlsx");
423
        headers.setContentLength(bos.toByteArray().length);
424
 
425
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(bos.toByteArray()));
426
        return new ResponseEntity<>(resource, headers, org.springframework.http.HttpStatus.OK);
427
    }
428
 
429
    private ByteArrayOutputStream buildVendorPricingChangesExcel(
430
            Map<Integer, Supplier> supplierMap,
431
            Map<Integer, List<VendorPriceCircularModel>> baselineByVendor,
432
            Map<Integer, List<VendorPriceCircularModel>> changesByVendor,
433
            Map<Integer, List<Item>> itemMap) throws Exception {
434
 
435
        XSSFWorkbook workbook = new XSSFWorkbook();
436
        XSSFSheet sheet = workbook.createSheet("Pricing Changes");
437
 
438
        CellStyle headerStyle = workbook.createCellStyle();
439
        Font boldFont = workbook.createFont();
440
        boldFont.setBold(true);
441
        headerStyle.setFont(boldFont);
442
 
443
        int rowNum = 0;
444
 
445
        XSSFRow colRow = sheet.createRow(rowNum++);
446
        String[] columns = {"Vendor", "Effective Date", "Model", "Catalog Id", "TP", "DP", "MOP"};
447
        for (int i = 0; i < columns.length; i++) {
448
            colRow.createCell(i).setCellValue(columns[i]);
449
            colRow.getCell(i).setCellStyle(headerStyle);
450
        }
451
 
452
        List<Map.Entry<Integer, Supplier>> sortedVendors = supplierMap.entrySet().stream()
453
                .sorted(Comparator.comparing(e -> e.getValue().getName()))
454
                .collect(Collectors.toList());
455
 
456
        for (Map.Entry<Integer, Supplier> vendorEntry : sortedVendors) {
457
            int vendorId = vendorEntry.getKey();
458
            String vendorName = vendorEntry.getValue().getName();
459
 
460
            List<VendorPriceCircularModel> baseline = baselineByVendor.getOrDefault(vendorId, Collections.emptyList());
461
            List<VendorPriceCircularModel> changes = changesByVendor.getOrDefault(vendorId, Collections.emptyList());
462
 
463
            if (baseline.isEmpty() && changes.isEmpty()) {
464
                continue;
465
            }
466
 
467
            Map<Integer, Float> tpTracker = new HashMap<>();
468
 
469
            for (VendorPriceCircularModel bp : baseline) {
470
                XSSFRow dataRow = sheet.createRow(rowNum++);
471
                dataRow.createCell(0).setCellValue(vendorName);
472
                dataRow.createCell(1).setCellValue(FormattingUtils.formatDate(bp.getEffectedOn()));
473
                dataRow.createCell(2).setCellValue(getModelName(itemMap, bp.getCatalogId()));
474
                dataRow.createCell(3).setCellValue(bp.getCatalogId());
475
                dataRow.createCell(4).setCellValue(bp.getTransferPrice());
476
                dataRow.createCell(5).setCellValue(bp.getDealerPrice());
477
                dataRow.createCell(6).setCellValue(bp.getMop());
478
                tpTracker.put(bp.getCatalogId(), bp.getTransferPrice());
479
            }
480
 
481
            for (VendorPriceCircularModel cp : changes) {
482
                Float lastTp = tpTracker.get(cp.getCatalogId());
483
                if (lastTp == null || Float.compare(lastTp, cp.getTransferPrice()) != 0) {
484
                    XSSFRow dataRow = sheet.createRow(rowNum++);
485
                    dataRow.createCell(0).setCellValue(vendorName);
486
                    dataRow.createCell(1).setCellValue(FormattingUtils.formatDate(cp.getEffectedOn()));
487
                    dataRow.createCell(2).setCellValue(getModelName(itemMap, cp.getCatalogId()));
488
                    dataRow.createCell(3).setCellValue(cp.getCatalogId());
489
                    dataRow.createCell(4).setCellValue(cp.getTransferPrice());
490
                    dataRow.createCell(5).setCellValue(cp.getDealerPrice());
491
                    dataRow.createCell(6).setCellValue(cp.getMop());
492
                    tpTracker.put(cp.getCatalogId(), cp.getTransferPrice());
493
                }
494
            }
495
        }
496
 
497
        for (int i = 0; i < 7; i++) {
498
            sheet.autoSizeColumn(i);
499
        }
500
 
501
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
502
        workbook.write(bos);
503
        workbook.close();
504
        return bos;
505
    }
506
 
507
    private String getModelName(Map<Integer, List<Item>> itemMap, int catalogId) {
508
        List<Item> items = itemMap.get(catalogId);
509
        if (items != null && !items.isEmpty()) {
510
            return items.get(0).getItemDescriptionNoColor();
511
        }
512
        return "Unknown (" + catalogId + ")";
513
    }
32075 tejbeer 514
}