Subversion Repositories SmartDukaan

Rev

Rev 32964 | Rev 33036 | 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;
6
import com.spice.profitmandi.common.util.Utils;
7
import com.spice.profitmandi.dao.entity.catalog.Item;
33035 amit.gupta 8
import com.spice.profitmandi.dao.entity.inventory.VendorCatalogPricing;
32952 amit.gupta 9
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
10
import com.spice.profitmandi.dao.entity.warehouse.Supplier;
11
import com.spice.profitmandi.dao.model.StateGstRateModel;
12
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
13
import com.spice.profitmandi.dao.repository.catalog.StateGstRateRepository;
33035 amit.gupta 14
import com.spice.profitmandi.dao.repository.inventory.VendorCatalogPricingLogRepository;
15
import com.spice.profitmandi.dao.repository.inventory.VendorCatalogPricingRepository;
32952 amit.gupta 16
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
17
import com.spice.profitmandi.dao.repository.warehouse.SupplierRepository;
33035 amit.gupta 18
import com.spice.profitmandi.service.inventory.VendorCatalogPricingService;
32952 amit.gupta 19
import in.shop2020.model.v1.catalog.status;
20
import org.apache.logging.log4j.LogManager;
21
import org.apache.logging.log4j.Logger;
22
import org.apache.poi.ss.usermodel.Cell;
23
import org.apache.poi.ss.usermodel.DateUtil;
24
import org.apache.poi.ss.usermodel.Row;
25
import org.apache.poi.xssf.usermodel.XSSFRow;
26
import org.apache.poi.xssf.usermodel.XSSFSheet;
27
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
28
import org.springframework.beans.factory.annotation.Autowired;
29
import org.springframework.stereotype.Component;
30
import org.springframework.web.multipart.MultipartFile;
31
 
32
import java.io.FileInputStream;
33
import java.time.LocalDateTime;
34
import java.util.Arrays;
35
import java.util.List;
36
import java.util.Map;
37
import java.util.stream.Collectors;
38
 
39
 
40
@Component
41
public class ItemLoaderService {
42
 
43
    private static List<Character> ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars().mapToObj(c -> (char) c).collect(Collectors.toList());
44
    @Autowired
45
    ItemRepository itemRepository;
46
 
47
    @Autowired
33035 amit.gupta 48
    VendorCatalogPricingRepository vendorCatalogPricingRepository;
49
 
50
    @Autowired
32952 amit.gupta 51
    StateGstRateRepository stateGstRateRepository;
52
 
53
    @Autowired
54
    VendorItemPricingRepository vendorItemPricingRepository;
55
 
56
    private static final Logger LOGGER = LogManager.getLogger(ItemLoaderService.class);
57
 
58
    public void parse(MultipartFile file) throws Exception {
59
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
60
 
61
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
62
        // Return first sheet from the XLSX workbook
63
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
64
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
65
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
66
            XSSFRow row = mySheet.getRow(rowNumber);
67
            ItemLoaderModel itemLoaderModel = this.createLoaderModel(row);
68
            try {
69
                this.addItem(itemLoaderModel);
70
            } catch (ProfitMandiBusinessException e) {
71
                throw new ProfitMandiBusinessException(e.getRejectedType(), e.getRejectedValue(), e.getCode() + "at " + itemLoaderModel.getRowIndex());
72
            }
73
        }
74
    }
75
 
76
 
77
    private String toAlphabet(int number) {
78
        StringBuffer sb = new StringBuffer();
79
        boolean loop = true;
80
        while (loop) {
81
            sb.append(ALPHABETS.get(number % 26));
82
            number = number / 26;
83
            loop = number > 0;
84
 
85
        }
86
        return sb.reverse().toString();
87
    }
88
 
89
    private ItemLoaderModel createLoaderModel(XSSFRow row) throws ProfitMandiBusinessException {
90
        ItemLoaderModel itemLoaderModel = new ItemLoaderModel();
91
        int i = 0;
92
        itemLoaderModel.setRowIndex(row.getRowNum());
93
        try {
94
            itemLoaderModel.setProductGroup(row.getCell(i++).getStringCellValue());
95
            itemLoaderModel.setCategoryId((int) row.getCell(i++).getNumericCellValue());
96
            itemLoaderModel.setCategory(row.getCell(i++).getStringCellValue());
97
            itemLoaderModel.setHsnCode(String.valueOf((int) row.getCell(i++).getNumericCellValue()));
98
            itemLoaderModel.setBrand(row.getCell(i++).getStringCellValue());
99
            itemLoaderModel.setModelNumber(row.getCell(i++).getStringCellValue());
32959 amit.gupta 100
            Cell modelCell = row.getCell(i++);
101
            if (modelCell == null) {
102
                itemLoaderModel.setModelName("");
103
            } else {
32964 amit.gupta 104
                itemLoaderModel.setModelName(modelCell.getStringCellValue());
32959 amit.gupta 105
            }
32952 amit.gupta 106
            itemLoaderModel.setColor(row.getCell(i++).getStringCellValue());
107
            //MRP	SP	MOP	DP	TP	NLC	Startdate	Preferred Vendor	Risky
108
            // Weight	Item type(1 for Serialized and 2 for non-serialized)	TaxRate
109
            itemLoaderModel.setMrp(row.getCell(i++).getNumericCellValue());
110
            itemLoaderModel.setSp(row.getCell(i++).getNumericCellValue());
111
            itemLoaderModel.setMop(row.getCell(i++).getNumericCellValue());
112
            itemLoaderModel.setDp(row.getCell(i++).getNumericCellValue());
113
            itemLoaderModel.setTp(row.getCell(i++).getNumericCellValue());
114
            itemLoaderModel.setNlc(row.getCell(i++).getNumericCellValue());
115
            itemLoaderModel.setStartDate(Utils.convertToLocalDateTime(row.getCell(i++).getDateCellValue()));
116
            itemLoaderModel.setPreferredVendor((int) (row.getCell(i++).getNumericCellValue()));
117
            itemLoaderModel.setRisky(row.getCell(i++).getNumericCellValue() == 0 ? false : true);
118
            itemLoaderModel.setWeight(row.getCell(i++).getNumericCellValue());
119
            itemLoaderModel.setItemType((int) row.getCell(i++).getNumericCellValue());
120
            itemLoaderModel.setTaxRate(row.getCell(i++).getNumericCellValue() * 100);
121
        } catch (Throwable e) {
32963 amit.gupta 122
            LOGGER.info(e.getCause());
32952 amit.gupta 123
            throw new ProfitMandiBusinessException("Field", "Field at row - " + row.getRowNum() + ", column - " + (i - 1),
124
                    "Invalid field value at - " + this.toAlphabet(i - 1) + (row.getRowNum() + 1) + ", " + this.getCellValue(row.getCell(i - 1)));
125
        }
126
        return itemLoaderModel;
127
    }
128
 
129
    @Autowired
130
    SupplierRepository supplierRepository;
131
 
132
    private void validateItemLoaderModel(ItemLoaderModel itemLoaderModel) throws ProfitMandiBusinessException {
133
        if (itemLoaderModel.getTaxRate() > 28)
134
            throw new ProfitMandiBusinessException("Tax Rate should not be above 28%", "", "");
135
        if (itemLoaderModel.getMrp() < itemLoaderModel.getSp())
136
            throw new ProfitMandiBusinessException("Selling Price should not be greater than MRP", "", "");
137
        Supplier supplier = supplierRepository.selectById(itemLoaderModel.getPreferredVendor());
138
        if (supplier == null) throw new ProfitMandiBusinessException("Invalid Supplier", "", "");
139
 
140
    }
141
 
142
    private String getCellValue(Cell cell) {
143
        if (cell == null) {
144
            return "Null cell";
145
        }
146
        switch (cell.getCellTypeEnum()) {
147
            case STRING:
148
                return cell.getStringCellValue();
149
            case NUMERIC:
150
                if (DateUtil.isCellDateFormatted(cell)) {
151
                    return cell.getDateCellValue().toString();
152
                } else {
153
                    return Double.toString(cell.getNumericCellValue());
154
                }
155
            case BOOLEAN:
156
                return Boolean.toString(cell.getBooleanCellValue());
157
            case FORMULA:
158
                return cell.getCellFormula();
159
            default:
160
                return "";
161
        }
162
    }
163
 
164
    //@Autowired
165
 
166
    private void addItem(ItemLoaderModel itemLoaderModel) throws ProfitMandiBusinessException {
167
        this.validateItemLoaderModel(itemLoaderModel);
168
        List<Item> items = itemRepository.selectAll(itemLoaderModel.getBrand(), itemLoaderModel.getModelName(), itemLoaderModel.getModelNumber());
169
        int catalogId = 0;
170
        if (items.size() > 0) {
32962 amit.gupta 171
            //Check if color already exist
172
            long similarColorCount = items.stream().filter(x-> itemLoaderModel.getColor().equals(x.getColorNatural())).count();
173
            if(similarColorCount > 0) {
174
                throw new ProfitMandiBusinessException("Color alerady exist", "Pls check", itemLoaderModel.getColor());
175
            }
176
 
32952 amit.gupta 177
            List<Integer> categoryIds = items.stream().map(x -> x.getCategoryId()).distinct().collect(Collectors.toList());
178
            if (categoryIds.size() > 1) {
179
                throw new ProfitMandiBusinessException("Model Wrongly Mapped to different categories", "Pls check", categoryIds.toString());
180
            } else if (categoryIds.get(0) != itemLoaderModel.getCategoryId()) {
181
                throw new ProfitMandiBusinessException("Model already Mapped to different category", "Pls check", categoryIds.toString());
182
            }
183
            List<Integer> catalogIds = items.stream().map(x -> x.getCategoryId()).distinct().collect(Collectors.toList());
184
            if (catalogIds.size() > 1) {
185
                throw new ProfitMandiBusinessException("Model Wrongly Mapped to different CatalogIds", "Pls check", catalogIds.toString());
186
            }
32962 amit.gupta 187
            Map<String, Long> colorsCount = items.stream().collect(Collectors.groupingBy(x -> x.getColorNatural(), Collectors.counting()));
32952 amit.gupta 188
            for (Map.Entry<String, Long> colorCountEntrySet : colorsCount.entrySet()) {
189
                if (colorCountEntrySet.getValue() > 1) {
190
                    throw new ProfitMandiBusinessException("Model repeats the same color", "Pls check", colorCountEntrySet.getKey());
191
                }
192
            }
193
            catalogId = items.get(0).getCatalogItemId();
194
        } else {
195
            catalogId = itemRepository.getNextEntity();
196
        }
197
        //Finally either got valid existing model or new model altogether
198
        Item item = new Item();
199
        item.setBrand(itemLoaderModel.getBrand());
200
        item.setModelName(itemLoaderModel.getModelName());
201
        item.setModelNumber(itemLoaderModel.getModelNumber());
202
        item.setColor(itemLoaderModel.getColor());
203
        item.setSellingPrice(new Float(Math.round(itemLoaderModel.getSp())));
204
        item.setMrp(new Float(Math.round(itemLoaderModel.getMrp())));
205
        item.setStartDate(itemLoaderModel.getStartDate());
206
        item.setCategoryId(itemLoaderModel.getCategoryId());
207
        item.setPreferredVendor(itemLoaderModel.getPreferredVendor());
208
        item.setRisky(itemLoaderModel.isRisky());
209
        item.setCatalogItemId(catalogId);
210
        if (itemLoaderModel.getWeight() <= 0) {
211
            throw new ProfitMandiBusinessException("Weight", "0", "Weight should be greater than 0");
212
        }
213
        item.setWeight(itemLoaderModel.getWeight());
214
        item.setStatus(status.PARTIALLY_ACTIVE);
215
        item.setUpdatedOn(LocalDateTime.now());
216
        item.setAddedOn(LocalDateTime.now());
217
 
218
        //if(item.getHsnCode())
219
        item.setHsnCode(itemLoaderModel.getHsnCode());
220
        ItemType itemType = ItemType.findByValue(itemLoaderModel.getItemType());
221
        if (itemType == null) {
222
            throw new ProfitMandiBusinessException("Item Type", "Invalid", "Should be 1 for SERIALIZED or 2 for Non Serialized");
223
        }
224
        item.setType(itemType);
225
        itemRepository.persist(item);
226
        //Logic for model here
227
 
228
        //Set Tax Rate
229
        StateGstRateModel stateGstRateModel = new StateGstRateModel();
230
        stateGstRateModel.setItemId(item.getId());
231
        stateGstRateModel.setIgstRate(itemLoaderModel.getTaxRate());
232
        stateGstRateRepository.addStateGstRates(Arrays.asList(stateGstRateModel));
233
 
234
        //Add Vendor
33035 amit.gupta 235
        this.addVendorItemPricing(item, itemLoaderModel);
32952 amit.gupta 236
    }
33035 amit.gupta 237
 
238
    private void addVendorItemPricing(Item item, ItemLoaderModel itemLoaderModel) {
239
        List<VendorCatalogPricing> vendorCatalogPricingList = vendorCatalogPricingRepository.selectByCatalogId(item.getCatalogItemId());
240
        for (VendorCatalogPricing vendorCatalogPricing : vendorCatalogPricingList) {
241
            VendorItemPricing vendorItemPricing = new VendorItemPricing();
242
            vendorItemPricing.setItemId(item.getId());
243
            vendorItemPricing.setVendorId(vendorCatalogPricing.getVendorId());
244
            vendorItemPricing.setDp(vendorCatalogPricing.getDealerPrice());
245
            vendorItemPricing.setMop(vendorCatalogPricing.getMop());
246
            vendorItemPricing.setNlc(vendorCatalogPricing.getTransferPrice());
247
            vendorItemPricing.setTp(vendorCatalogPricing.getTransferPrice());
248
            vendorItemPricingRepository.persist(vendorItemPricing);
249
        }
250
    }
32952 amit.gupta 251
    /*
252
 
253
    item = Item()
254
    item.productGroup = product_group
255
    item.brand = brand
256
    item.modelNumber = model_number
257
    item.modelName = model_name
258
    item.color = color
259
            try:
260
    item.mrp = round(mrp)
261
    except:
262
    pass
263
            #if item is risky
264
            if categoryMap.has_key(category_name.strip()):
265
    item.category = categoryMap[category_name.strip()]
266
    item.itemStatus = 8
267
            else:
268
    print "can't find {0} at row {1}".format(category_name, rownum)
269
                continue
270
    item.sellingPrice = round(sp)
271
    item.startDate = long(to_java_date(datetime.datetime(1899, 12, 30) + timedelta(days=int(start_date))))
272
    item.preferredVendor = preferred_vendor
273
    item.risky = int(risky)
274
    item.weight = weight
275
    item.updatedOn = updatedOn
276
    item.type = int(item_type)
277
 
278
    cclient = CatalogClient().get_client()
279
                    for c1 in (5,5,5,5,5):
280
            try:
281
            prodClient.addItem(item)
282
            if len(states) > 0:
283
            for c3 in (1,2,3,4,5):
284
            try:
285
            prodClient.updateItemStateVat(item_id, states)
286
    print "break 1"
287
            break
288
    except Exception as e:
289
    prodClient = CatalogClient("catalog_service_server_host_prod").get_client()
290
    print "break 2"
291
            break
292
    except:
293
    prodClient = CatalogClient("catalog_service_server_host_prod").get_client()
294
    print "break 3"
295
            break
296
    except Exception as e:
297
    cclient = CatalogClient().get_client()
298
    vip = VendorItemPricing()
299
    vip.itemId = item_id
300
    vip.dealerPrice = round(dp)
301
    vip.mop = round(mop)
302
    vip.nlc = round(nlc)
303
    vip.transferPrice = round(tp)
304
    vip.vendorId = preferred_vendor
305
            for c in (1,2,3,4,5):
306
            try:
307
            iclient.addVendorItemPricing(vip)
308
            break
309
    except Exception as e:
310
    iclient = InventoryClient().get_client()
311
 
312
    except:
313
            traceback.print_exc()
314
    message = message + "\t" + str(brand) + "\t" + str(model_name) + "\t" + str(model_number) + "\t" + "\n"
315
    print message
316
    mail("build@shop2020.in", "cafe@nes", ["amit.gupta@shop2020.in", "chandan.kumar@shop2020.in"], "Problem while adding items", message, [], [], [])
317
    print "Successfully updated the item list information."
318
 
319
 
320
    def main():
321
    parser = optparse.OptionParser()
322
            parser.add_option("-f", "--file", dest="filename",
323
    default="ItemList.xls", type="string",
324
    help="Read the item list from FILE",
325
    metavar="FILE")
326
            (options, args) = parser.parse_args()
327
            if len(args) != 0:
328
            parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
329
    filename = options.filename
330
    load_item_data(filename)
331
 
332
if __name__ == '__main__':
333
    main()
334
*/
335
}