Subversion Repositories SmartDukaan

Rev

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