Subversion Repositories SmartDukaan

Rev

Rev 5290 | Rev 5306 | 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;
6
import in.shop2020.model.v1.catalog.ItemType;
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
 
4990 mandeep.dh 18
import java.io.File;
19
import java.util.ArrayList;
4987 mandeep.dh 20
import java.util.HashMap;
21
import java.util.List;
22
import java.util.Map;
23
 
5212 mandeep.dh 24
import javax.mail.MessagingException;
25
 
490 rajveer 26
import org.apache.struts2.rest.DefaultHttpHeaders;
27
import org.apache.struts2.rest.HttpHeaders;
5212 mandeep.dh 28
import org.apache.thrift.TException;
3104 chandransh 29
import org.slf4j.Logger;
30
import org.slf4j.LoggerFactory;
31
 
490 rajveer 32
import com.opensymphony.xwork2.ModelDriven;
33
 
1367 chandransh 34
public class UpdatesController implements ModelDriven<InventoryUpdate>{
490 rajveer 35
 
4987 mandeep.dh 36
    /**
37
     * 
38
     */
39
    private static final String FIELD_DELIMITER = "~#~#~#";
40
 
3104 chandransh 41
    private static Logger logger = LoggerFactory.getLogger(UpdatesController.class);
42
 
490 rajveer 43
	private InventoryUpdate inventoryUpdate = new InventoryUpdate();
4987 mandeep.dh 44
	private String timestampAndItemIds;
490 rajveer 45
 
5237 mandeep.dh 46
	private Map<Long, String> hotspotMappings = new HashMap<Long, String>();
47
 
490 rajveer 48
	private int errorCode = 0;
49
	private String errorMessage;
5210 mandeep.dh 50
	private boolean fullPlbSync = false;
490 rajveer 51
	private String id;
52
 
53
 
54
	public UpdatesController(){
55
 
56
	}
57
 
58
	@Override
1367 chandransh 59
	public InventoryUpdate getModel() {
490 rajveer 60
		return this.inventoryUpdate;
61
	}
62
 
63
	public HttpHeaders show(){
3104 chandransh 64
		logger.info("Status requested for warehouse id: " + getId());
3125 rajveer 65
		CatalogClient catalogServiceClient;
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
 
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(),
125
                            mapping.getItemKey());
126
                }
127
            }
128
        } catch (Exception e) {
5284 mandeep.dh 129
            logger.error("Could not load vendor item mappings. Trying to reload.", e);
5304 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) {
187
			                currentInventory.put(plbDetail.getItemKey(), plbDetail);
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) {
219
                if (ItemType.NON_SERIALIZED.equals(item.getType())) {
220
                    continue;
221
                }
222
 
5237 mandeep.dh 223
                if (hotspotMappings.containsKey(item.getId())) {
224
                    PLBDetails plbDetails = currentInventory
225
                            .get(hotspotMappings.get(item.getId()));
226
                    Long currentSnapshotAvailibility = item.getItemInventory()
227
                            .getAvailability().get(warehouseId);
228
                    if ((currentSnapshotAvailibility == null || currentSnapshotAvailibility.equals(0)) && 
5241 mandeep.dh 229
                        (plbDetails == null || plbDetails.getQuantity().longValue() == 0))
5237 mandeep.dh 230
                    {
231
                        continue;
232
                    }
5223 mandeep.dh 233
 
5237 mandeep.dh 234
                    if (currentSnapshotAvailibility == null || plbDetails == null ||
235
                        !currentSnapshotAvailibility.equals(plbDetails.getQuantity().longValue()))
236
                    {
237
                        mismatches.put(item, plbDetails);
5212 mandeep.dh 238
                    }
239
                }
240
            }
241
 
242
            String subject = mismatches.size() + " mismatches with PLB sync for warehouse id: " + warehouseId;
5223 mandeep.dh 243
            StringBuilder body = new StringBuilder("Item Id\tBrand\tModel Name\tModel Number\tColor\tSpice Online Retail\tHotspot\n");
5212 mandeep.dh 244
            for (Item item : mismatches.keySet()) {
5223 mandeep.dh 245
                Long currentSnapshotAvailability = item.getItemInventory().getAvailability().get(warehouseId);
246
                String plbQuantity = mismatches.get(item) == null ? "0" : mismatches.get(item).getQuantity().toString();
247
                String currentSnapshotQuantity = currentSnapshotAvailability == null ? "0" : currentSnapshotAvailability.toString();
248
                body.append(item.getId() + "\t" + item.getBrand() + "\t" + item.getModelName() + "\t" + item.getModelNumber() + "\t" + item.getColor() + "\t" + currentSnapshotQuantity + "\t" + plbQuantity + "\n");
5212 mandeep.dh 249
            }
5220 mandeep.dh 250
 
251
            logger.info(body.toString());
5212 mandeep.dh 252
            GmailUtils g = new GmailUtils();
5223 mandeep.dh 253
            g.sendSSLMessage(new String[]{ "mandeep.dhir@shop2020.in" }, subject, body.toString(), "cnc.center@shop2020.in", "5h0p2o2o", new ArrayList<File>());
5212 mandeep.dh 254
        }
255
    }
256
 
490 rajveer 257
	public int getErrorCode() {
258
		return errorCode;
259
	}
260
 
261
	public String getErrorMessage() {
262
		return errorMessage;
263
	}
264
 
265
	public String getId(){
266
		return id;
267
	}
268
 
269
	public void setId(String id){
270
		this.id = id;
271
	}
272
 
273
	public InventoryUpdate getInventoryUpdate() {
274
		return inventoryUpdate;
275
	}
276
 
277
	public void setInventoryUpdate(InventoryUpdate inventoryUpdate) {
278
		this.inventoryUpdate = inventoryUpdate;
279
	}
280
 
4987 mandeep.dh 281
	public void setTimestampAndItemIds(String timestampAndItemIds) {
282
		this.timestampAndItemIds = timestampAndItemIds;
490 rajveer 283
	}
284
 
4987 mandeep.dh 285
	public String getTimestampAndItemIds() {
286
		return timestampAndItemIds;
5210 mandeep.dh 287
	}
288
 
289
    public boolean isFullPlbSync() {
290
        return fullPlbSync;
291
    }
292
 
293
    public void setFullPlbSync(boolean fullPlbSync) {
294
        this.fullPlbSync = fullPlbSync;
295
    }	
490 rajveer 296
}