Subversion Repositories SmartDukaan

Rev

Rev 5448 | Rev 5597 | 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);
5395 mandeep.dh 99
            return fetchItems();
5285 mandeep.dh 100
        }
101
    }
102
 
5306 rajveer 103
	/**
104
     * @return
105
     */
106
    private ItemInventory fetchInventory(long itemId) {
107
        try {
108
            Client snapshotClient = new CatalogClient().getClient();
109
            return snapshotClient.getItemInventoryByItemId(itemId);
110
        } catch (Exception e) {
111
            logger.error("Could not fetch all items. Retrying.", e);
112
            return fetchInventory(itemId);
113
        }
114
    }
5448 mandeep.dh 115
 
5285 mandeep.dh 116
    /**
5237 mandeep.dh 117
     * 
118
     */
119
    private void loadHotspotMappings() {
120
        try {
121
            Client snapshotClient = new CatalogClient().getClient();
5284 mandeep.dh 122
            for (VendorItemMapping mapping : snapshotClient.getAllVendorItemMappings()) {
5237 mandeep.dh 123
                if (mapping.getVendorId() == 1) {
124
                    hotspotMappings.put(mapping.getItemId(),
5448 mandeep.dh 125
                            mapping.getItemKey().trim().toLowerCase());
5237 mandeep.dh 126
                }
127
            }
128
        } catch (Exception e) {
5284 mandeep.dh 129
            logger.error("Could not load vendor item mappings. Trying to reload.", e);
5395 mandeep.dh 130
            loadHotspotMappings();
5237 mandeep.dh 131
        }
132
    }
133
 
134
    /**
3326 chandransh 135
	 * Stores the inventory updates on the history and the production server.
136
	 * @return
137
	 */
490 rajveer 138
	public HttpHeaders create(){
3104 chandransh 139
		logger.info(inventoryUpdate.toString());
490 rajveer 140
		try {
3326 chandransh 141
		    //The snapshot client is used to update the inventory snapshot for production systems.
142
		    CatalogClient snapshotCatalogServiceClient = new CatalogClient();
143
			Client snapshotClient = snapshotCatalogServiceClient.getClient();
144
 
145
	         //The history client is used to update the inventory history on the processing system.
146
            CatalogClient historyCatalogServiceClient = new CatalogClient(
147
                    ConfigClientKeys.inventory_history_service_server_host.toString(),
148
                    ConfigClientKeys.inventory_history_service_server_port.toString());
149
			Client historyClient = historyCatalogServiceClient.getClient();
4585 rajveer 150
 
151
		    //The snapshot client is used to update the inventory snapshot for production systems.
152
		    TransactionClient transactionClient = new TransactionClient();
153
			in.shop2020.model.v1.order.TransactionService.Client tClient = transactionClient.getClient();
154
 
490 rajveer 155
			Long warehouseId = Long.parseLong(inventoryUpdate.getwarehouseId());
156
			String timestamp = inventoryUpdate.getCurrentTimestamp();
157
			Map<String, Long> availability = new HashMap<String, Long>();
158
			List<Update> updates = inventoryUpdate.getUpdates();
5230 mandeep.dh 159
			if (updates != null) {
160
	            for(Update update: updates){
161
	                String key = update.getKey();
162
	                long quantity = (long) Double.parseDouble(update.getQuantity());
163
	                if(availability.containsKey(key)){
164
	                    quantity = quantity + availability.get(key);
165
	                }
166
	                availability.put(key, quantity);
167
	            }			    
490 rajveer 168
			}
4585 rajveer 169
 
3326 chandransh 170
			//Update the snapshot before the history since that is more important.
171
			snapshotClient.updateInventory(warehouseId, timestamp, availability);
172
			historyClient.updateInventoryHistory(warehouseId, timestamp, availability);
4585 rajveer 173
 
174
			List<BillingUpdate> billingUpdates = inventoryUpdate.getBillingUpdates();
175
			if(billingUpdates!=null){
176
				for(BillingUpdate billingUpdate: billingUpdates){
4765 rajveer 177
					tClient.addInvoiceNumber(Long.parseLong(billingUpdate.getOrderId()), billingUpdate.getInvoiceNumber(), billingUpdate.getColor());
4585 rajveer 178
				}
179
			}
4987 mandeep.dh 180
 
181
			List<PLBDetails> plbDetails = inventoryUpdate.getPlbDetails();
182
			if (plbDetails != null) {
5212 mandeep.dh 183
			    Map<String, PLBDetails> currentInventory = new HashMap<String, PLBDetails>();
4987 mandeep.dh 184
			    for (PLBDetails plbDetail : plbDetails) {
185
			        try {
5212 mandeep.dh 186
			            if (fullPlbSync) {
5451 mandeep.dh 187
			                currentInventory.put(plbDetail.getItemKey().toLowerCase(), plbDetail);
5212 mandeep.dh 188
			            }
189
			            else {
190
	                        snapshotClient.resetAvailability(
191
	                                plbDetail.getItemKey(), 1,
192
	                                plbDetail.getQuantity().longValue(), warehouseId);
193
	                        snapshotClient.markMissedInventoryUpdatesAsProcessed(
194
	                                plbDetail.getItemKey(), warehouseId);			                
195
			            }
4987 mandeep.dh 196
                    } catch (Exception e) {
197
                        logger.error("Could not reset availability of: " + plbDetail.getItemKey(), e);
4990 mandeep.dh 198
                        GmailUtils g = new GmailUtils();
199
                        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 200
                    }
201
			    }
5212 mandeep.dh 202
 
5218 mandeep.dh 203
			    sendMailForPLBMismatches(warehouseId, currentInventory);
4987 mandeep.dh 204
			}
490 rajveer 205
		} catch (Exception e) {
3104 chandransh 206
			logger.error("Unable to update inventory", e);
490 rajveer 207
		}
5220 mandeep.dh 208
 
490 rajveer 209
		return new DefaultHttpHeaders("psuccess");
210
	}
211
 
5218 mandeep.dh 212
    private void sendMailForPLBMismatches(Long warehouseId, Map<String, PLBDetails> currentInventory)
5212 mandeep.dh 213
            throws InventoryServiceException, TException, MessagingException {
214
        if (fullPlbSync) {
5237 mandeep.dh 215
            loadHotspotMappings();
5212 mandeep.dh 216
            Map<Item, PLBDetails> mismatches = new HashMap<Item, PLBDetails>();
5290 mandeep.dh 217
            List<Item> items = fetchItems();
5212 mandeep.dh 218
            for (Item item : items) {
5237 mandeep.dh 219
                if (hotspotMappings.containsKey(item.getId())) {
220
                    PLBDetails plbDetails = currentInventory
5448 mandeep.dh 221
                            .get(hotspotMappings.get(item.getId()).trim().toLowerCase());
5423 rajveer 222
                    Long currentSnapshotAvailability = fetchInventory(item.getId()).getAvailability().get(warehouseId);
223
                    if ((currentSnapshotAvailability == null || currentSnapshotAvailability.equals(0l)) && 
5241 mandeep.dh 224
                        (plbDetails == null || plbDetails.getQuantity().longValue() == 0))
5237 mandeep.dh 225
                    {
226
                        continue;
227
                    }
5223 mandeep.dh 228
 
5423 rajveer 229
                    if (currentSnapshotAvailability == null || plbDetails == null ||
230
                        !currentSnapshotAvailability.equals(plbDetails.getQuantity().longValue()))
5237 mandeep.dh 231
                    {
232
                        mismatches.put(item, plbDetails);
5212 mandeep.dh 233
                    }
234
                }
235
            }
236
 
237
            String subject = mismatches.size() + " mismatches with PLB sync for warehouse id: " + warehouseId;
5223 mandeep.dh 238
            StringBuilder body = new StringBuilder("Item Id\tBrand\tModel Name\tModel Number\tColor\tSpice Online Retail\tHotspot\n");
5212 mandeep.dh 239
            for (Item item : mismatches.keySet()) {
5306 rajveer 240
                Long currentSnapshotAvailability = fetchInventory(item.getId()).getAvailability().get(warehouseId);
5223 mandeep.dh 241
                String plbQuantity = mismatches.get(item) == null ? "0" : mismatches.get(item).getQuantity().toString();
242
                String currentSnapshotQuantity = currentSnapshotAvailability == null ? "0" : currentSnapshotAvailability.toString();
243
                body.append(item.getId() + "\t" + item.getBrand() + "\t" + item.getModelName() + "\t" + item.getModelNumber() + "\t" + item.getColor() + "\t" + currentSnapshotQuantity + "\t" + plbQuantity + "\n");
5212 mandeep.dh 244
            }
5220 mandeep.dh 245
 
246
            logger.info(body.toString());
5212 mandeep.dh 247
            GmailUtils g = new GmailUtils();
5223 mandeep.dh 248
            g.sendSSLMessage(new String[]{ "mandeep.dhir@shop2020.in" }, subject, body.toString(), "cnc.center@shop2020.in", "5h0p2o2o", new ArrayList<File>());
5212 mandeep.dh 249
        }
250
    }
251
 
490 rajveer 252
	public int getErrorCode() {
253
		return errorCode;
254
	}
255
 
256
	public String getErrorMessage() {
257
		return errorMessage;
258
	}
259
 
260
	public String getId(){
261
		return id;
262
	}
263
 
264
	public void setId(String id){
265
		this.id = id;
266
	}
267
 
268
	public InventoryUpdate getInventoryUpdate() {
269
		return inventoryUpdate;
270
	}
271
 
272
	public void setInventoryUpdate(InventoryUpdate inventoryUpdate) {
273
		this.inventoryUpdate = inventoryUpdate;
274
	}
275
 
4987 mandeep.dh 276
	public void setTimestampAndItemIds(String timestampAndItemIds) {
277
		this.timestampAndItemIds = timestampAndItemIds;
490 rajveer 278
	}
279
 
4987 mandeep.dh 280
	public String getTimestampAndItemIds() {
281
		return timestampAndItemIds;
5210 mandeep.dh 282
	}
283
 
284
    public boolean isFullPlbSync() {
285
        return fullPlbSync;
286
    }
287
 
288
    public void setFullPlbSync(boolean fullPlbSync) {
289
        this.fullPlbSync = fullPlbSync;
290
    }	
490 rajveer 291
}