Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
32952 amit.gupta 1
package com.spice.profitmandi.service.catalog;
2
 
3
 
4
import com.spice.profitmandi.common.enumuration.ItemType;
5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33172 tejus.loha 6
import com.spice.profitmandi.common.util.ExcelUtils;
37071 amit 7
import com.spice.profitmandi.common.util.StringUtils;
32952 amit.gupta 8
import com.spice.profitmandi.common.util.Utils;
33771 amit.gupta 9
import com.spice.profitmandi.dao.entity.catalog.BrandCatalog;
10
import com.spice.profitmandi.dao.entity.catalog.Catalog;
35343 ranu 11
import com.spice.profitmandi.dao.entity.catalog.CategorisedCatalog;
32952 amit.gupta 12
import com.spice.profitmandi.dao.entity.catalog.Item;
33035 amit.gupta 13
import com.spice.profitmandi.dao.entity.inventory.VendorCatalogPricing;
32952 amit.gupta 14
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
15
import com.spice.profitmandi.dao.entity.warehouse.Supplier;
35343 ranu 16
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
32952 amit.gupta 17
import com.spice.profitmandi.dao.model.StateGstRateModel;
35343 ranu 18
import com.spice.profitmandi.dao.repository.catalog.*;
33035 amit.gupta 19
import com.spice.profitmandi.dao.repository.inventory.VendorCatalogPricingRepository;
32952 amit.gupta 20
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
21
import com.spice.profitmandi.dao.repository.warehouse.SupplierRepository;
22
import in.shop2020.model.v1.catalog.status;
23
import org.apache.logging.log4j.LogManager;
24
import org.apache.logging.log4j.Logger;
25
import org.apache.poi.ss.usermodel.Cell;
26
import org.apache.poi.ss.usermodel.Row;
27
import org.apache.poi.xssf.usermodel.XSSFRow;
28
import org.apache.poi.xssf.usermodel.XSSFSheet;
29
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
30
import org.springframework.beans.factory.annotation.Autowired;
31
import org.springframework.stereotype.Component;
32
import org.springframework.web.multipart.MultipartFile;
33
 
35343 ranu 34
import java.time.LocalDate;
32952 amit.gupta 35
import java.time.LocalDateTime;
36
import java.util.Arrays;
37
import java.util.List;
38
import java.util.Map;
39
import java.util.stream.Collectors;
40
 
41
 
42
@Component
43
public class ItemLoaderService {
44
 
45
    @Autowired
33771 amit.gupta 46
    BrandsRepository brandsRepository;
47
 
48
    @Autowired
32952 amit.gupta 49
    ItemRepository itemRepository;
50
 
51
    @Autowired
33035 amit.gupta 52
    VendorCatalogPricingRepository vendorCatalogPricingRepository;
53
 
54
    @Autowired
32952 amit.gupta 55
    StateGstRateRepository stateGstRateRepository;
56
 
57
    @Autowired
58
    VendorItemPricingRepository vendorItemPricingRepository;
59
 
33172 tejus.loha 60
 
32952 amit.gupta 61
    private static final Logger LOGGER = LogManager.getLogger(ItemLoaderService.class);
62
 
63
    public void parse(MultipartFile file) throws Exception {
64
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
65
 
66
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
67
        // Return first sheet from the XLSX workbook
68
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
69
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
70
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
71
            XSSFRow row = mySheet.getRow(rowNumber);
72
            ItemLoaderModel itemLoaderModel = this.createLoaderModel(row);
73
            try {
33346 amit.gupta 74
                LOGGER.info("rownum - {}", rowNumber);
32952 amit.gupta 75
                this.addItem(itemLoaderModel);
76
            } catch (ProfitMandiBusinessException e) {
77
                throw new ProfitMandiBusinessException(e.getRejectedType(), e.getRejectedValue(), e.getCode() + "at " + itemLoaderModel.getRowIndex());
78
            }
79
        }
80
    }
81
 
82
 
83
 
84
 
85
    private ItemLoaderModel createLoaderModel(XSSFRow row) throws ProfitMandiBusinessException {
86
        ItemLoaderModel itemLoaderModel = new ItemLoaderModel();
87
        int i = 0;
88
        itemLoaderModel.setRowIndex(row.getRowNum());
89
        try {
33037 amit.gupta 90
            itemLoaderModel.setProductGroup(row.getCell(i++).getStringCellValue().trim());
32952 amit.gupta 91
            itemLoaderModel.setCategoryId((int) row.getCell(i++).getNumericCellValue());
33037 amit.gupta 92
            itemLoaderModel.setCategory(row.getCell(i++).getStringCellValue().trim());
32952 amit.gupta 93
            itemLoaderModel.setHsnCode(String.valueOf((int) row.getCell(i++).getNumericCellValue()));
37071 amit 94
            itemLoaderModel.setBrand(StringUtils.normalizeWhitespace(row.getCell(i++).getStringCellValue()));
33771 amit.gupta 95
            Cell modelNumberCell = row.getCell(i++);
37071 amit 96
            if(modelNumberCell== null || StringUtils.normalizeWhitespace(modelNumberCell.getStringCellValue()).isEmpty()) {
33771 amit.gupta 97
                throw new Exception("Model Number cant be null or empty");
98
            } else {
37071 amit 99
                itemLoaderModel.setModelNumber(StringUtils.normalizeWhitespace(modelNumberCell.getStringCellValue()));
33771 amit.gupta 100
            }
101
            Cell modelNameCell = row.getCell(i++);
102
            if (modelNameCell == null) {
32959 amit.gupta 103
                itemLoaderModel.setModelName("");
104
            } else {
37071 amit 105
                itemLoaderModel.setModelName(StringUtils.normalizeWhitespace(modelNameCell.getStringCellValue()));
32959 amit.gupta 106
            }
37071 amit 107
            itemLoaderModel.setColor(StringUtils.normalizeWhitespace(row.getCell(i++).getStringCellValue()));
32952 amit.gupta 108
            //MRP	SP	MOP	DP	TP	NLC	Startdate	Preferred Vendor	Risky
109
            // Weight	Item type(1 for Serialized and 2 for non-serialized)	TaxRate
110
            itemLoaderModel.setMrp(row.getCell(i++).getNumericCellValue());
111
            itemLoaderModel.setSp(row.getCell(i++).getNumericCellValue());
112
            itemLoaderModel.setMop(row.getCell(i++).getNumericCellValue());
113
            itemLoaderModel.setDp(row.getCell(i++).getNumericCellValue());
114
            itemLoaderModel.setTp(row.getCell(i++).getNumericCellValue());
115
            itemLoaderModel.setNlc(row.getCell(i++).getNumericCellValue());
116
            itemLoaderModel.setStartDate(Utils.convertToLocalDateTime(row.getCell(i++).getDateCellValue()));
117
            itemLoaderModel.setPreferredVendor((int) (row.getCell(i++).getNumericCellValue()));
118
            itemLoaderModel.setRisky(row.getCell(i++).getNumericCellValue() == 0 ? false : true);
119
            itemLoaderModel.setWeight(row.getCell(i++).getNumericCellValue());
120
            itemLoaderModel.setItemType((int) row.getCell(i++).getNumericCellValue());
121
            itemLoaderModel.setTaxRate(row.getCell(i++).getNumericCellValue() * 100);
37218 amit 122
            // optional trailing column: brand's own SKU/article code
123
            Cell brandIdentifierCell = row.getCell(i++);
124
            if (brandIdentifierCell != null) {
125
                itemLoaderModel.setBrandIdentifier(
126
                        StringUtils.normalizeWhitespace(brandIdentifierCell.getStringCellValue()));
127
            }
32952 amit.gupta 128
        } catch (Throwable e) {
32963 amit.gupta 129
            LOGGER.info(e.getCause());
32952 amit.gupta 130
            throw new ProfitMandiBusinessException("Field", "Field at row - " + row.getRowNum() + ", column - " + (i - 1),
33173 amit.gupta 131
                    "Invalid field value at - " + ExcelUtils.toAlphabet(i - 1) + (row.getRowNum() + 1) + ", " + ExcelUtils.getCellValue(row.getCell(i - 1)));
32952 amit.gupta 132
        }
133
        return itemLoaderModel;
134
    }
135
 
136
    @Autowired
137
    SupplierRepository supplierRepository;
138
 
139
    private void validateItemLoaderModel(ItemLoaderModel itemLoaderModel) throws ProfitMandiBusinessException {
34663 aman.kumar 140
        if (Utils.compareDouble(itemLoaderModel.getTaxRate(), 28d) > 0)
32952 amit.gupta 141
            throw new ProfitMandiBusinessException("Tax Rate should not be above 28%", "", "");
142
        if (itemLoaderModel.getMrp() < itemLoaderModel.getSp())
143
            throw new ProfitMandiBusinessException("Selling Price should not be greater than MRP", "", "");
144
        Supplier supplier = supplierRepository.selectById(itemLoaderModel.getPreferredVendor());
145
        if (supplier == null) throw new ProfitMandiBusinessException("Invalid Supplier", "", "");
146
 
147
    }
148
 
149
 
33172 tejus.loha 150
 
33771 amit.gupta 151
    @Autowired
152
    CatalogRepository catalogRepository;
32952 amit.gupta 153
 
35343 ranu 154
    @Autowired
155
    CategorisedCatalogRepository categorisedCatalogRepository;
156
 
32952 amit.gupta 157
    private void addItem(ItemLoaderModel itemLoaderModel) throws ProfitMandiBusinessException {
158
        this.validateItemLoaderModel(itemLoaderModel);
33771 amit.gupta 159
        Catalog catalog = catalogRepository.selectCatalog(itemLoaderModel.getBrand(), itemLoaderModel.getModelNumber(), itemLoaderModel.getModelName());
160
        if (catalog != null) {
161
            List<Item> items = itemRepository.selectAllByCatalogItemId(catalog.getId());
33172 tejus.loha 162
            long similarColorCount = items.stream().filter(x -> itemLoaderModel.getColor().equals(x.getColorNatural())).count();
163
            if (similarColorCount > 0) {
34709 amit.gupta 164
                throw new ProfitMandiBusinessException("Color already exist", "Pls check", itemLoaderModel.getColor());
32962 amit.gupta 165
            }
166
 
32952 amit.gupta 167
            List<Integer> categoryIds = items.stream().map(x -> x.getCategoryId()).distinct().collect(Collectors.toList());
168
            if (categoryIds.size() > 1) {
169
                throw new ProfitMandiBusinessException("Model Wrongly Mapped to different categories", "Pls check", categoryIds.toString());
170
            } else if (categoryIds.get(0) != itemLoaderModel.getCategoryId()) {
171
                throw new ProfitMandiBusinessException("Model already Mapped to different category", "Pls check", categoryIds.toString());
172
            }
173
            List<Integer> catalogIds = items.stream().map(x -> x.getCategoryId()).distinct().collect(Collectors.toList());
174
            if (catalogIds.size() > 1) {
175
                throw new ProfitMandiBusinessException("Model Wrongly Mapped to different CatalogIds", "Pls check", catalogIds.toString());
176
            }
32962 amit.gupta 177
            Map<String, Long> colorsCount = items.stream().collect(Collectors.groupingBy(x -> x.getColorNatural(), Collectors.counting()));
32952 amit.gupta 178
            for (Map.Entry<String, Long> colorCountEntrySet : colorsCount.entrySet()) {
179
                if (colorCountEntrySet.getValue() > 1) {
180
                    throw new ProfitMandiBusinessException("Model repeats the same color", "Pls check", colorCountEntrySet.getKey());
181
                }
182
            }
35343 ranu 183
 
184
            CategorisedCatalog categorisedCatalog = categorisedCatalogRepository.getCurrentCatalogMovement(catalog.getId());
185
            if (categorisedCatalog == null) {
186
                CategorisedCatalog categorisedCatalogNew = new CategorisedCatalog();
187
                categorisedCatalogNew.setCatalogId(catalog.getId());
188
                categorisedCatalogNew.setStatus(CatalogMovingEnum.RUNNING);
189
                categorisedCatalogNew.setStartDate(LocalDate.now());
190
                categorisedCatalogRepository.persist(categorisedCatalogNew);
191
            } else if (categorisedCatalog.getStatus().equals(CatalogMovingEnum.OTHER)) {
192
                categorisedCatalog.setStatus(CatalogMovingEnum.SLOWMOVING);
193
            }
194
 
32952 amit.gupta 195
        } else {
33771 amit.gupta 196
            catalog = new Catalog();
197
            BrandCatalog brand = brandsRepository.selectByBrand(itemLoaderModel.getBrand());
198
            if(brand == null) {
199
                    throw new ProfitMandiBusinessException("Brand Does not exist", "Pls check", itemLoaderModel.getBrand());
200
            }
201
            catalog.setBrandId(brand.getId());
202
            catalog.setBrand(itemLoaderModel.getBrand());
203
            catalog.setModelName(itemLoaderModel.getModelName());
204
            catalog.setModelNumber(itemLoaderModel.getModelNumber());
33888 ranu 205
            catalog.setCategoryId(itemLoaderModel.getCategoryId());
33771 amit.gupta 206
            catalog.setCreated(LocalDateTime.now());
207
            catalog.setCreatedBy("System");
208
            catalogRepository.persist(catalog);
35343 ranu 209
 
210
 
211
            CategorisedCatalog categorisedCatalog = new CategorisedCatalog();
212
            categorisedCatalog.setCatalogId(catalog.getId());
213
            categorisedCatalog.setStatus(CatalogMovingEnum.RUNNING);
214
            categorisedCatalog.setStartDate(LocalDate.now());
215
            categorisedCatalogRepository.persist(categorisedCatalog);
32952 amit.gupta 216
        }
217
        //Finally either got valid existing model or new model altogether
218
        Item item = new Item();
219
        item.setBrand(itemLoaderModel.getBrand());
220
        item.setModelName(itemLoaderModel.getModelName());
221
        item.setModelNumber(itemLoaderModel.getModelNumber());
222
        item.setColor(itemLoaderModel.getColor());
223
        item.setSellingPrice(new Float(Math.round(itemLoaderModel.getSp())));
224
        item.setMrp(new Float(Math.round(itemLoaderModel.getMrp())));
225
        item.setStartDate(itemLoaderModel.getStartDate());
226
        item.setCategoryId(itemLoaderModel.getCategoryId());
227
        item.setPreferredVendor(itemLoaderModel.getPreferredVendor());
228
        item.setRisky(itemLoaderModel.isRisky());
33771 amit.gupta 229
        item.setCatalogItemId(catalog.getId());
37218 amit 230
        if (itemLoaderModel.getBrandIdentifier() != null && !itemLoaderModel.getBrandIdentifier().isEmpty()) {
231
            item.setBrandIdentifier(itemLoaderModel.getBrandIdentifier());
232
        }
32952 amit.gupta 233
        if (itemLoaderModel.getWeight() <= 0) {
234
            throw new ProfitMandiBusinessException("Weight", "0", "Weight should be greater than 0");
235
        }
236
        item.setWeight(itemLoaderModel.getWeight());
237
        item.setStatus(status.PARTIALLY_ACTIVE);
238
        item.setUpdatedOn(LocalDateTime.now());
239
        item.setAddedOn(LocalDateTime.now());
240
 
241
        //if(item.getHsnCode())
242
        item.setHsnCode(itemLoaderModel.getHsnCode());
243
        ItemType itemType = ItemType.findByValue(itemLoaderModel.getItemType());
244
        if (itemType == null) {
245
            throw new ProfitMandiBusinessException("Item Type", "Invalid", "Should be 1 for SERIALIZED or 2 for Non Serialized");
246
        }
247
        item.setType(itemType);
248
        itemRepository.persist(item);
249
        //Logic for model here
250
 
251
        //Set Tax Rate
252
        StateGstRateModel stateGstRateModel = new StateGstRateModel();
253
        stateGstRateModel.setItemId(item.getId());
254
        stateGstRateModel.setIgstRate(itemLoaderModel.getTaxRate());
255
        stateGstRateRepository.addStateGstRates(Arrays.asList(stateGstRateModel));
256
 
257
        //Add Vendor
33036 amit.gupta 258
        this.addVendorItemPricing(item);
32952 amit.gupta 259
    }
33035 amit.gupta 260
 
33036 amit.gupta 261
    private void addVendorItemPricing(Item item) {
33035 amit.gupta 262
        List<VendorCatalogPricing> vendorCatalogPricingList = vendorCatalogPricingRepository.selectByCatalogId(item.getCatalogItemId());
263
        for (VendorCatalogPricing vendorCatalogPricing : vendorCatalogPricingList) {
264
            VendorItemPricing vendorItemPricing = new VendorItemPricing();
265
            vendorItemPricing.setItemId(item.getId());
266
            vendorItemPricing.setVendorId(vendorCatalogPricing.getVendorId());
267
            vendorItemPricing.setDp(vendorCatalogPricing.getDealerPrice());
268
            vendorItemPricing.setMop(vendorCatalogPricing.getMop());
269
            vendorItemPricing.setNlc(vendorCatalogPricing.getTransferPrice());
270
            vendorItemPricing.setTp(vendorCatalogPricing.getTransferPrice());
271
            vendorItemPricingRepository.persist(vendorItemPricing);
272
        }
273
    }
32952 amit.gupta 274
 
275
}