Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
490 rajveer 1
package in.shop2020.support.controllers;
2
 
5945 mandeep.dh 3
import in.shop2020.model.v1.inventory.InventoryService.Client;
4
import in.shop2020.model.v1.inventory.InventoryServiceException;
5210 mandeep.dh 5
import in.shop2020.model.v1.catalog.Item;
5945 mandeep.dh 6
import in.shop2020.model.v1.inventory.ItemInventory;
7
import in.shop2020.model.v1.inventory.VendorItemMapping;
8
import in.shop2020.model.v1.inventory.Warehouse;
4585 rajveer 9
import in.shop2020.support.models.BillingUpdate;
490 rajveer 10
import in.shop2020.support.models.InventoryUpdate;
4987 mandeep.dh 11
import in.shop2020.support.models.PLBDetails;
490 rajveer 12
import in.shop2020.support.models.Update;
3125 rajveer 13
import in.shop2020.thrift.clients.CatalogClient;
5945 mandeep.dh 14
import in.shop2020.thrift.clients.InventoryClient;
4585 rajveer 15
import in.shop2020.thrift.clients.TransactionClient;
3326 chandransh 16
import in.shop2020.utils.ConfigClientKeys;
4990 mandeep.dh 17
import in.shop2020.utils.GmailUtils;
490 rajveer 18
 
5684 mandeep.dh 19
import java.io.BufferedWriter;
4990 mandeep.dh 20
import java.io.File;
5684 mandeep.dh 21
import java.io.FileWriter;
22
import java.io.IOException;
4990 mandeep.dh 23
import java.util.ArrayList;
4987 mandeep.dh 24
import java.util.HashMap;
25
import java.util.List;
26
import java.util.Map;
27
 
5212 mandeep.dh 28
import javax.mail.MessagingException;
29
 
5684 mandeep.dh 30
import org.apache.commons.lang.StringUtils;
490 rajveer 31
import org.apache.struts2.rest.DefaultHttpHeaders;
32
import org.apache.struts2.rest.HttpHeaders;
5212 mandeep.dh 33
import org.apache.thrift.TException;
5690 mandeep.dh 34
import org.apache.thrift.transport.TTransportException;
3104 chandransh 35
import org.slf4j.Logger;
36
import org.slf4j.LoggerFactory;
37
 
490 rajveer 38
import com.opensymphony.xwork2.ModelDriven;
39
 
1367 chandransh 40
public class UpdatesController implements ModelDriven<InventoryUpdate>{
490 rajveer 41
 
4987 mandeep.dh 42
    /**
43
     * 
44
     */
5945 mandeep.dh 45
    private static final int HOTSPOT_VENDOR_ID = 1;
46
 
47
    /**
48
     * 
49
     */
4987 mandeep.dh 50
    private static final String FIELD_DELIMITER = "~#~#~#";
51
 
3104 chandransh 52
    private static Logger logger = LoggerFactory.getLogger(UpdatesController.class);
53
 
490 rajveer 54
	private InventoryUpdate inventoryUpdate = new InventoryUpdate();
4987 mandeep.dh 55
	private String timestampAndItemIds;
490 rajveer 56
 
5945 mandeep.dh 57
	private Map<Long, List<String>> hotspotMappings = new HashMap<Long, List<String>>();
5237 mandeep.dh 58
 
490 rajveer 59
	private int errorCode = 0;
60
	private String errorMessage;
5210 mandeep.dh 61
	private boolean fullPlbSync = false;
490 rajveer 62
	private String id;
5690 mandeep.dh 63
 
64
    private Client snapshotClient;
490 rajveer 65
 
66
 
67
	public UpdatesController(){
68
 
69
	}
70
 
71
	@Override
1367 chandransh 72
	public InventoryUpdate getModel() {
490 rajveer 73
		return this.inventoryUpdate;
74
	}
75
 
76
	public HttpHeaders show(){
3104 chandransh 77
		logger.info("Status requested for warehouse id: " + getId());
490 rajveer 78
		Client client;
79
 
80
		try {
5945 mandeep.dh 81
			client = new InventoryClient().getClient();
490 rajveer 82
			long warehouseId = Long.parseLong(getId());
83
			Warehouse warehouse = client.getWarehouse(warehouseId);
4987 mandeep.dh 84
			timestampAndItemIds = warehouse.getVendorString();
5210 mandeep.dh 85
 
5395 mandeep.dh 86
			List<String> itemKeys = new ArrayList<String>();
5210 mandeep.dh 87
 
5395 mandeep.dh 88
			if (!fullPlbSync) {
5945 mandeep.dh 89
			    client = new InventoryClient().getClient();
5395 mandeep.dh 90
			    itemKeys = client.getItemKeysToBeProcessed(warehouseId);
5210 mandeep.dh 91
			}
92
 
5395 mandeep.dh 93
			for (String itemKey : itemKeys) {
94
			    timestampAndItemIds += FIELD_DELIMITER + itemKey;
4987 mandeep.dh 95
			}
490 rajveer 96
		} catch (Exception e) {
3104 chandransh 97
			logger.error("Error getting the warehouse or setting the timestamp", e);
490 rajveer 98
		}
99
		return new DefaultHttpHeaders("lsuccess");
100
	}
101
 
3326 chandransh 102
	/**
5285 mandeep.dh 103
     * @return
104
     */
105
    private List<Item> fetchItems() {
106
        try {
5945 mandeep.dh 107
            in.shop2020.model.v1.catalog.CatalogService.Client snapshotClient = new CatalogClient().getClient();
5285 mandeep.dh 108
            return snapshotClient.getAllItems(true);
109
        } catch (Exception e) {
110
            logger.error("Could not fetch all items. Retrying.", e);
5597 mandeep.dh 111
            try {
112
                Thread.sleep(30000 * Long.parseLong(inventoryUpdate.getwarehouseId()));
113
            } catch (Exception e1) {
114
                logger.error("Could not sleep.", e1);
115
            }
116
 
5395 mandeep.dh 117
            return fetchItems();
5285 mandeep.dh 118
        }
119
    }
120
 
5306 rajveer 121
	/**
122
     * @return
123
     */
124
    private ItemInventory fetchInventory(long itemId) {
125
        try {
126
            return snapshotClient.getItemInventoryByItemId(itemId);
127
        } catch (Exception e) {
128
            logger.error("Could not fetch all items. Retrying.", e);
5690 mandeep.dh 129
            try {
5945 mandeep.dh 130
                snapshotClient = new InventoryClient().getClient();
5690 mandeep.dh 131
                return fetchInventory(itemId);
132
            } catch (TTransportException e1) {
133
                logger.error("Could not create client", e);
134
                return null;
135
            }
5306 rajveer 136
        }
137
    }
5448 mandeep.dh 138
 
5285 mandeep.dh 139
    /**
5237 mandeep.dh 140
     * 
141
     */
142
    private void loadHotspotMappings() {
143
        try {
5284 mandeep.dh 144
            for (VendorItemMapping mapping : snapshotClient.getAllVendorItemMappings()) {
5945 mandeep.dh 145
                if (mapping.getVendorId() == HOTSPOT_VENDOR_ID) {
146
                    long itemId = mapping.getItemId();
147
                    if (!hotspotMappings.containsKey(itemId)) {
148
                        hotspotMappings.put(itemId, new ArrayList<String>());
149
                    }
150
 
151
                    hotspotMappings.get(itemId).add(mapping.getItemKey().trim().toLowerCase());
5237 mandeep.dh 152
                }
153
            }
154
        } catch (Exception e) {
5284 mandeep.dh 155
            logger.error("Could not load vendor item mappings. Trying to reload.", e);
5597 mandeep.dh 156
 
157
            try {
158
                Thread.sleep(30000 * Long.parseLong(inventoryUpdate.getwarehouseId()));
159
            } catch (Exception e1) {
160
                logger.error("Could not sleep.", e1);
161
            }
162
 
5690 mandeep.dh 163
            try {
5945 mandeep.dh 164
                snapshotClient = new InventoryClient().getClient();
5690 mandeep.dh 165
                loadHotspotMappings();
166
            } catch (TTransportException e1) {
167
                logger.error("Could not create client", e);
168
            }
5237 mandeep.dh 169
        }
170
    }
171
 
172
    /**
3326 chandransh 173
	 * Stores the inventory updates on the history and the production server.
174
	 * @return
175
	 */
490 rajveer 176
	public HttpHeaders create(){
3104 chandransh 177
		logger.info(inventoryUpdate.toString());
490 rajveer 178
		try {
3326 chandransh 179
		    //The snapshot client is used to update the inventory snapshot for production systems.
5945 mandeep.dh 180
		    InventoryClient snapshotCatalogServiceClient = new InventoryClient();
3326 chandransh 181
			Client snapshotClient = snapshotCatalogServiceClient.getClient();
182
 
183
	         //The history client is used to update the inventory history on the processing system.
5945 mandeep.dh 184
            InventoryClient historyInventoryServiceClient = new InventoryClient(
3326 chandransh 185
                    ConfigClientKeys.inventory_history_service_server_host.toString(),
186
                    ConfigClientKeys.inventory_history_service_server_port.toString());
5945 mandeep.dh 187
			Client historyClient = historyInventoryServiceClient.getClient();
4585 rajveer 188
 
5945 mandeep.dh 189
			Client stagingCatalogClient = new InventoryClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
5702 mandeep.dh 190
                    ConfigClientKeys.catalog_service_server_port.toString()).getClient();
191
 
4585 rajveer 192
		    //The snapshot client is used to update the inventory snapshot for production systems.
193
		    TransactionClient transactionClient = new TransactionClient();
194
			in.shop2020.model.v1.order.TransactionService.Client tClient = transactionClient.getClient();
195
 
490 rajveer 196
			Long warehouseId = Long.parseLong(inventoryUpdate.getwarehouseId());
197
			String timestamp = inventoryUpdate.getCurrentTimestamp();
198
			Map<String, Long> availability = new HashMap<String, Long>();
199
			List<Update> updates = inventoryUpdate.getUpdates();
5230 mandeep.dh 200
			if (updates != null) {
201
	            for(Update update: updates){
202
	                String key = update.getKey();
203
	                long quantity = (long) Double.parseDouble(update.getQuantity());
204
	                if(availability.containsKey(key)){
205
	                    quantity = quantity + availability.get(key);
206
	                }
207
	                availability.put(key, quantity);
208
	            }			    
490 rajveer 209
			}
4585 rajveer 210
 
3326 chandransh 211
			//Update the snapshot before the history since that is more important.
212
			snapshotClient.updateInventory(warehouseId, timestamp, availability);
5712 mandeep.dh 213
			stagingCatalogClient.updateVendorString(warehouseId, timestamp);
3326 chandransh 214
			historyClient.updateInventoryHistory(warehouseId, timestamp, availability);
4585 rajveer 215
 
216
			List<BillingUpdate> billingUpdates = inventoryUpdate.getBillingUpdates();
217
			if(billingUpdates!=null){
218
				for(BillingUpdate billingUpdate: billingUpdates){
4765 rajveer 219
					tClient.addInvoiceNumber(Long.parseLong(billingUpdate.getOrderId()), billingUpdate.getInvoiceNumber(), billingUpdate.getColor());
4585 rajveer 220
				}
221
			}
4987 mandeep.dh 222
 
223
			List<PLBDetails> plbDetails = inventoryUpdate.getPlbDetails();
224
			if (plbDetails != null) {
5212 mandeep.dh 225
			    Map<String, PLBDetails> currentInventory = new HashMap<String, PLBDetails>();
4987 mandeep.dh 226
			    for (PLBDetails plbDetail : plbDetails) {
227
			        try {
5212 mandeep.dh 228
			            if (fullPlbSync) {
5451 mandeep.dh 229
			                currentInventory.put(plbDetail.getItemKey().toLowerCase(), plbDetail);
5212 mandeep.dh 230
			            }
231
			            else {
232
	                        snapshotClient.resetAvailability(
233
	                                plbDetail.getItemKey(), 1,
234
	                                plbDetail.getQuantity().longValue(), warehouseId);
235
	                        snapshotClient.markMissedInventoryUpdatesAsProcessed(
5702 mandeep.dh 236
	                                plbDetail.getItemKey(), warehouseId);
5212 mandeep.dh 237
			            }
4987 mandeep.dh 238
                    } catch (Exception e) {
239
                        logger.error("Could not reset availability of: " + plbDetail.getItemKey(), e);
4990 mandeep.dh 240
                        GmailUtils g = new GmailUtils();
241
                        g.sendSSLMessage(new String[]{ "mandeep.dhir@shop2020.in" }, "Error resetting availability for " + plbDetail.getItemKey() + " in warehouseId: " + warehouseId + " to " + plbDetail.getQuantity(), "", "cnc.center@shop2020.in", "5hop2o2o", new ArrayList<File>());
4987 mandeep.dh 242
                    }
243
			    }
5212 mandeep.dh 244
 
5218 mandeep.dh 245
			    sendMailForPLBMismatches(warehouseId, currentInventory);
4987 mandeep.dh 246
			}
490 rajveer 247
		} catch (Exception e) {
3104 chandransh 248
			logger.error("Unable to update inventory", e);
490 rajveer 249
		}
5220 mandeep.dh 250
 
490 rajveer 251
		return new DefaultHttpHeaders("psuccess");
252
	}
253
 
5218 mandeep.dh 254
    private void sendMailForPLBMismatches(Long warehouseId, Map<String, PLBDetails> currentInventory)
5212 mandeep.dh 255
            throws InventoryServiceException, TException, MessagingException {
256
        if (fullPlbSync) {
5945 mandeep.dh 257
            snapshotClient = new InventoryClient().getClient();
5237 mandeep.dh 258
            loadHotspotMappings();
5212 mandeep.dh 259
            Map<Item, PLBDetails> mismatches = new HashMap<Item, PLBDetails>();
5290 mandeep.dh 260
            List<Item> items = fetchItems();
5212 mandeep.dh 261
            for (Item item : items) {
5237 mandeep.dh 262
                if (hotspotMappings.containsKey(item.getId())) {
5945 mandeep.dh 263
                    PLBDetails plbDetails = null;
264
                    for (String s : hotspotMappings.get(item.getId())) {
265
                        if (currentInventory.containsKey(s.trim().toLowerCase())) {
266
                            plbDetails = currentInventory.get(s.trim().toLowerCase());
267
                        }
268
                    }
269
 
5423 rajveer 270
                    Long currentSnapshotAvailability = fetchInventory(item.getId()).getAvailability().get(warehouseId);
271
                    if ((currentSnapshotAvailability == null || currentSnapshotAvailability.equals(0l)) && 
5241 mandeep.dh 272
                        (plbDetails == null || plbDetails.getQuantity().longValue() == 0))
5237 mandeep.dh 273
                    {
274
                        continue;
275
                    }
5223 mandeep.dh 276
 
5423 rajveer 277
                    if (currentSnapshotAvailability == null || plbDetails == null ||
278
                        !currentSnapshotAvailability.equals(plbDetails.getQuantity().longValue()))
5237 mandeep.dh 279
                    {
280
                        mismatches.put(item, plbDetails);
5212 mandeep.dh 281
                    }
282
                }
283
            }
284
 
285
            String subject = mismatches.size() + " mismatches with PLB sync for warehouse id: " + warehouseId;
5684 mandeep.dh 286
            File file = new File("mismatches.xls");
287
 
288
            try {
289
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
290
                bufferedWriter.write(StringUtils.join(new String[] { "Item Id",
291
                        "Brand", "Model Name", "Model Number",
292
                        "Color", "SpiceOnlineRetailStock", "HotspotStock" }, '\t'));
293
                for (Item item : mismatches.keySet()) {
294
                    Long currentSnapshotAvailability = fetchInventory(item.getId()).getAvailability().get(warehouseId);
295
                    String plbQuantity = mismatches.get(item) == null ? "0" : mismatches.get(item).getQuantity().toString();
296
                    String currentSnapshotQuantity = currentSnapshotAvailability == null ? "0" : currentSnapshotAvailability.toString();
297
                    bufferedWriter.newLine();
298
                    bufferedWriter.write(StringUtils.join(new String[] { String.valueOf(item.getId()), item.getBrand(), item.getModelName(),
299
                            item.getModelNumber(), item.getColor(),currentSnapshotQuantity, plbQuantity }, "\t"));
300
                }
301
 
302
                bufferedWriter.close();
303
            } catch (IOException e) {
304
                logger.error("Could not write mismatches to file", e);
5212 mandeep.dh 305
            }
5220 mandeep.dh 306
 
5212 mandeep.dh 307
            GmailUtils g = new GmailUtils();
5779 mandeep.dh 308
            g.sendSSLMessage(new String[]{ "mandeep.dhir@shop2020.in", "sandeep.sachdeva@shop2020.in", "ashutosh.saxena@shop2020.in", "rajneesh.arora@shop2020.in", "pankaj.kankar@shop2020.in" }, subject, 
5684 mandeep.dh 309
                    "", "cnc.center@shop2020.in", "5h0p2o2o", file.getAbsolutePath());
5212 mandeep.dh 310
        }
311
    }
312
 
490 rajveer 313
	public int getErrorCode() {
314
		return errorCode;
315
	}
316
 
317
	public String getErrorMessage() {
318
		return errorMessage;
319
	}
320
 
321
	public String getId(){
322
		return id;
323
	}
324
 
325
	public void setId(String id){
326
		this.id = id;
327
	}
328
 
329
	public InventoryUpdate getInventoryUpdate() {
330
		return inventoryUpdate;
331
	}
332
 
333
	public void setInventoryUpdate(InventoryUpdate inventoryUpdate) {
334
		this.inventoryUpdate = inventoryUpdate;
335
	}
336
 
4987 mandeep.dh 337
	public void setTimestampAndItemIds(String timestampAndItemIds) {
338
		this.timestampAndItemIds = timestampAndItemIds;
490 rajveer 339
	}
340
 
4987 mandeep.dh 341
	public String getTimestampAndItemIds() {
342
		return timestampAndItemIds;
5210 mandeep.dh 343
	}
344
 
345
    public boolean isFullPlbSync() {
346
        return fullPlbSync;
347
    }
348
 
349
    public void setFullPlbSync(boolean fullPlbSync) {
350
        this.fullPlbSync = fullPlbSync;
5684 mandeep.dh 351
    }
490 rajveer 352
}