Subversion Repositories SmartDukaan

Rev

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