Subversion Repositories SmartDukaan

Rev

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