Subversion Repositories SmartDukaan

Rev

Rev 5702 | Rev 5779 | 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
 
5702 mandeep.dh 179
			Client stagingCatalogClient = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
180
                    ConfigClientKeys.catalog_service_server_port.toString()).getClient();
181
 
4585 rajveer 182
		    //The snapshot client is used to update the inventory snapshot for production systems.
183
		    TransactionClient transactionClient = new TransactionClient();
184
			in.shop2020.model.v1.order.TransactionService.Client tClient = transactionClient.getClient();
185
 
490 rajveer 186
			Long warehouseId = Long.parseLong(inventoryUpdate.getwarehouseId());
187
			String timestamp = inventoryUpdate.getCurrentTimestamp();
188
			Map<String, Long> availability = new HashMap<String, Long>();
189
			List<Update> updates = inventoryUpdate.getUpdates();
5230 mandeep.dh 190
			if (updates != null) {
191
	            for(Update update: updates){
192
	                String key = update.getKey();
193
	                long quantity = (long) Double.parseDouble(update.getQuantity());
194
	                if(availability.containsKey(key)){
195
	                    quantity = quantity + availability.get(key);
196
	                }
197
	                availability.put(key, quantity);
198
	            }			    
490 rajveer 199
			}
4585 rajveer 200
 
3326 chandransh 201
			//Update the snapshot before the history since that is more important.
202
			snapshotClient.updateInventory(warehouseId, timestamp, availability);
5712 mandeep.dh 203
			stagingCatalogClient.updateVendorString(warehouseId, timestamp);
3326 chandransh 204
			historyClient.updateInventoryHistory(warehouseId, timestamp, availability);
4585 rajveer 205
 
206
			List<BillingUpdate> billingUpdates = inventoryUpdate.getBillingUpdates();
207
			if(billingUpdates!=null){
208
				for(BillingUpdate billingUpdate: billingUpdates){
4765 rajveer 209
					tClient.addInvoiceNumber(Long.parseLong(billingUpdate.getOrderId()), billingUpdate.getInvoiceNumber(), billingUpdate.getColor());
4585 rajveer 210
				}
211
			}
4987 mandeep.dh 212
 
213
			List<PLBDetails> plbDetails = inventoryUpdate.getPlbDetails();
214
			if (plbDetails != null) {
5212 mandeep.dh 215
			    Map<String, PLBDetails> currentInventory = new HashMap<String, PLBDetails>();
4987 mandeep.dh 216
			    for (PLBDetails plbDetail : plbDetails) {
217
			        try {
5212 mandeep.dh 218
			            if (fullPlbSync) {
5451 mandeep.dh 219
			                currentInventory.put(plbDetail.getItemKey().toLowerCase(), plbDetail);
5212 mandeep.dh 220
			            }
221
			            else {
222
	                        snapshotClient.resetAvailability(
223
	                                plbDetail.getItemKey(), 1,
224
	                                plbDetail.getQuantity().longValue(), warehouseId);
225
	                        snapshotClient.markMissedInventoryUpdatesAsProcessed(
5702 mandeep.dh 226
	                                plbDetail.getItemKey(), warehouseId);
5212 mandeep.dh 227
			            }
4987 mandeep.dh 228
                    } catch (Exception e) {
229
                        logger.error("Could not reset availability of: " + plbDetail.getItemKey(), e);
4990 mandeep.dh 230
                        GmailUtils g = new GmailUtils();
231
                        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 232
                    }
233
			    }
5212 mandeep.dh 234
 
5218 mandeep.dh 235
			    sendMailForPLBMismatches(warehouseId, currentInventory);
4987 mandeep.dh 236
			}
490 rajveer 237
		} catch (Exception e) {
3104 chandransh 238
			logger.error("Unable to update inventory", e);
490 rajveer 239
		}
5220 mandeep.dh 240
 
490 rajveer 241
		return new DefaultHttpHeaders("psuccess");
242
	}
243
 
5218 mandeep.dh 244
    private void sendMailForPLBMismatches(Long warehouseId, Map<String, PLBDetails> currentInventory)
5212 mandeep.dh 245
            throws InventoryServiceException, TException, MessagingException {
246
        if (fullPlbSync) {
5690 mandeep.dh 247
            snapshotClient = new CatalogClient().getClient();
5237 mandeep.dh 248
            loadHotspotMappings();
5212 mandeep.dh 249
            Map<Item, PLBDetails> mismatches = new HashMap<Item, PLBDetails>();
5290 mandeep.dh 250
            List<Item> items = fetchItems();
5212 mandeep.dh 251
            for (Item item : items) {
5237 mandeep.dh 252
                if (hotspotMappings.containsKey(item.getId())) {
5690 mandeep.dh 253
                    PLBDetails plbDetails = currentInventory.get(hotspotMappings.get(item.getId()).trim().toLowerCase());
5423 rajveer 254
                    Long currentSnapshotAvailability = fetchInventory(item.getId()).getAvailability().get(warehouseId);
255
                    if ((currentSnapshotAvailability == null || currentSnapshotAvailability.equals(0l)) && 
5241 mandeep.dh 256
                        (plbDetails == null || plbDetails.getQuantity().longValue() == 0))
5237 mandeep.dh 257
                    {
258
                        continue;
259
                    }
5223 mandeep.dh 260
 
5423 rajveer 261
                    if (currentSnapshotAvailability == null || plbDetails == null ||
262
                        !currentSnapshotAvailability.equals(plbDetails.getQuantity().longValue()))
5237 mandeep.dh 263
                    {
264
                        mismatches.put(item, plbDetails);
5212 mandeep.dh 265
                    }
266
                }
267
            }
268
 
269
            String subject = mismatches.size() + " mismatches with PLB sync for warehouse id: " + warehouseId;
5684 mandeep.dh 270
            File file = new File("mismatches.xls");
271
 
272
            try {
273
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
274
                bufferedWriter.write(StringUtils.join(new String[] { "Item Id",
275
                        "Brand", "Model Name", "Model Number",
276
                        "Color", "SpiceOnlineRetailStock", "HotspotStock" }, '\t'));
277
                for (Item item : mismatches.keySet()) {
278
                    Long currentSnapshotAvailability = fetchInventory(item.getId()).getAvailability().get(warehouseId);
279
                    String plbQuantity = mismatches.get(item) == null ? "0" : mismatches.get(item).getQuantity().toString();
280
                    String currentSnapshotQuantity = currentSnapshotAvailability == null ? "0" : currentSnapshotAvailability.toString();
281
                    bufferedWriter.newLine();
282
                    bufferedWriter.write(StringUtils.join(new String[] { String.valueOf(item.getId()), item.getBrand(), item.getModelName(),
283
                            item.getModelNumber(), item.getColor(),currentSnapshotQuantity, plbQuantity }, "\t"));
284
                }
285
 
286
                bufferedWriter.close();
287
            } catch (IOException e) {
288
                logger.error("Could not write mismatches to file", e);
5212 mandeep.dh 289
            }
5220 mandeep.dh 290
 
5212 mandeep.dh 291
            GmailUtils g = new GmailUtils();
5684 mandeep.dh 292
            g.sendSSLMessage(new String[]{ "mandeep.dhir@shop2020.in", "sandeep.sachdeva@shop2020.in", "ashutosh.saxena@shop2020.in" }, subject, 
293
                    "", "cnc.center@shop2020.in", "5h0p2o2o", file.getAbsolutePath());
5212 mandeep.dh 294
        }
295
    }
296
 
490 rajveer 297
	public int getErrorCode() {
298
		return errorCode;
299
	}
300
 
301
	public String getErrorMessage() {
302
		return errorMessage;
303
	}
304
 
305
	public String getId(){
306
		return id;
307
	}
308
 
309
	public void setId(String id){
310
		this.id = id;
311
	}
312
 
313
	public InventoryUpdate getInventoryUpdate() {
314
		return inventoryUpdate;
315
	}
316
 
317
	public void setInventoryUpdate(InventoryUpdate inventoryUpdate) {
318
		this.inventoryUpdate = inventoryUpdate;
319
	}
320
 
4987 mandeep.dh 321
	public void setTimestampAndItemIds(String timestampAndItemIds) {
322
		this.timestampAndItemIds = timestampAndItemIds;
490 rajveer 323
	}
324
 
4987 mandeep.dh 325
	public String getTimestampAndItemIds() {
326
		return timestampAndItemIds;
5210 mandeep.dh 327
	}
328
 
329
    public boolean isFullPlbSync() {
330
        return fullPlbSync;
331
    }
332
 
333
    public void setFullPlbSync(boolean fullPlbSync) {
334
        this.fullPlbSync = fullPlbSync;
5684 mandeep.dh 335
    }
490 rajveer 336
}