Subversion Repositories SmartDukaan

Rev

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