Subversion Repositories SmartDukaan

Rev

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