Subversion Repositories SmartDukaan

Rev

Rev 5304 | Rev 5395 | 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
 
5240 mandeep.dh 74
			client = new CatalogClient().getClient();
4987 mandeep.dh 75
			List<String> itemKeys = client.getItemKeysToBeProcessed(warehouseId);
5210 mandeep.dh 76
			if (fullPlbSync) {
5237 mandeep.dh 77
			    loadHotspotMappings();
5210 mandeep.dh 78
			    itemKeys = new ArrayList<String>();
5285 mandeep.dh 79
			    List<Item> items = fetchItems();
5210 mandeep.dh 80
			    for (Item item : items) {
81
			        if (ItemType.NON_SERIALIZED.equals(item.getType())) {
82
			            continue;
83
			        }
84
 
5237 mandeep.dh 85
			        if (hotspotMappings.containsKey(item.getId())) {
86
			            itemKeys.add(hotspotMappings.get(item.getId()));
5210 mandeep.dh 87
			        }
88
			    }
89
			}
90
 
4987 mandeep.dh 91
			if (!itemKeys.isEmpty()) {
92
			    for (String itemKey : itemKeys) {
93
			        timestampAndItemIds += FIELD_DELIMITER + itemKey;
94
			    }
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 {
107
            Client snapshotClient = new CatalogClient().getClient();
108
            return snapshotClient.getAllItems(true);
109
        } catch (Exception e) {
110
            logger.error("Could not fetch all items. Retrying.", e);
5304 mandeep.dh 111
//            return fetchItems();
112
            return new ArrayList<Item>();
5285 mandeep.dh 113
        }
114
    }
115
 
5306 rajveer 116
	/**
117
     * @return
118
     */
119
    private ItemInventory fetchInventory(long itemId) {
120
        try {
121
            Client snapshotClient = new CatalogClient().getClient();
122
            return snapshotClient.getItemInventoryByItemId(itemId);
123
        } catch (Exception e) {
124
            logger.error("Could not fetch all items. Retrying.", e);
125
            return fetchInventory(itemId);
126
        }
127
    }
128
 
5285 mandeep.dh 129
    /**
5237 mandeep.dh 130
     * 
131
     */
132
    private void loadHotspotMappings() {
133
        try {
134
            Client snapshotClient = new CatalogClient().getClient();
5284 mandeep.dh 135
            for (VendorItemMapping mapping : snapshotClient.getAllVendorItemMappings()) {
5237 mandeep.dh 136
                if (mapping.getVendorId() == 1) {
137
                    hotspotMappings.put(mapping.getItemId(),
138
                            mapping.getItemKey());
139
                }
140
            }
141
        } catch (Exception e) {
5284 mandeep.dh 142
            logger.error("Could not load vendor item mappings. Trying to reload.", e);
5304 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) {
200
			                currentInventory.put(plbDetail.getItemKey(), plbDetail);
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) {
232
                if (ItemType.NON_SERIALIZED.equals(item.getType())) {
233
                    continue;
234
                }
235
 
5237 mandeep.dh 236
                if (hotspotMappings.containsKey(item.getId())) {
237
                    PLBDetails plbDetails = currentInventory
238
                            .get(hotspotMappings.get(item.getId()));
5306 rajveer 239
                    Long currentSnapshotAvailibility = fetchInventory(item.getId()).getAvailability().get(warehouseId);
5237 mandeep.dh 240
                    if ((currentSnapshotAvailibility == null || currentSnapshotAvailibility.equals(0)) && 
5241 mandeep.dh 241
                        (plbDetails == null || plbDetails.getQuantity().longValue() == 0))
5237 mandeep.dh 242
                    {
243
                        continue;
244
                    }
5223 mandeep.dh 245
 
5237 mandeep.dh 246
                    if (currentSnapshotAvailibility == null || plbDetails == null ||
247
                        !currentSnapshotAvailibility.equals(plbDetails.getQuantity().longValue()))
248
                    {
249
                        mismatches.put(item, plbDetails);
5212 mandeep.dh 250
                    }
251
                }
252
            }
253
 
254
            String subject = mismatches.size() + " mismatches with PLB sync for warehouse id: " + warehouseId;
5223 mandeep.dh 255
            StringBuilder body = new StringBuilder("Item Id\tBrand\tModel Name\tModel Number\tColor\tSpice Online Retail\tHotspot\n");
5212 mandeep.dh 256
            for (Item item : mismatches.keySet()) {
5306 rajveer 257
                Long currentSnapshotAvailability = fetchInventory(item.getId()).getAvailability().get(warehouseId);
5223 mandeep.dh 258
                String plbQuantity = mismatches.get(item) == null ? "0" : mismatches.get(item).getQuantity().toString();
259
                String currentSnapshotQuantity = currentSnapshotAvailability == null ? "0" : currentSnapshotAvailability.toString();
260
                body.append(item.getId() + "\t" + item.getBrand() + "\t" + item.getModelName() + "\t" + item.getModelNumber() + "\t" + item.getColor() + "\t" + currentSnapshotQuantity + "\t" + plbQuantity + "\n");
5212 mandeep.dh 261
            }
5220 mandeep.dh 262
 
263
            logger.info(body.toString());
5212 mandeep.dh 264
            GmailUtils g = new GmailUtils();
5223 mandeep.dh 265
            g.sendSSLMessage(new String[]{ "mandeep.dhir@shop2020.in" }, subject, body.toString(), "cnc.center@shop2020.in", "5h0p2o2o", new ArrayList<File>());
5212 mandeep.dh 266
        }
267
    }
268
 
490 rajveer 269
	public int getErrorCode() {
270
		return errorCode;
271
	}
272
 
273
	public String getErrorMessage() {
274
		return errorMessage;
275
	}
276
 
277
	public String getId(){
278
		return id;
279
	}
280
 
281
	public void setId(String id){
282
		this.id = id;
283
	}
284
 
285
	public InventoryUpdate getInventoryUpdate() {
286
		return inventoryUpdate;
287
	}
288
 
289
	public void setInventoryUpdate(InventoryUpdate inventoryUpdate) {
290
		this.inventoryUpdate = inventoryUpdate;
291
	}
292
 
4987 mandeep.dh 293
	public void setTimestampAndItemIds(String timestampAndItemIds) {
294
		this.timestampAndItemIds = timestampAndItemIds;
490 rajveer 295
	}
296
 
4987 mandeep.dh 297
	public String getTimestampAndItemIds() {
298
		return timestampAndItemIds;
5210 mandeep.dh 299
	}
300
 
301
    public boolean isFullPlbSync() {
302
        return fullPlbSync;
303
    }
304
 
305
    public void setFullPlbSync(boolean fullPlbSync) {
306
        this.fullPlbSync = fullPlbSync;
307
    }	
490 rajveer 308
}