Stock Query

Query how much stock we have of a specific item.

Request Parameters

Each request to the web sevice requires a number of parameters, all of which are listed below. All requests require a key which will be sent to you by your account manager.

Name Type Default Description
ApiKey* String The key used to authenticate with the service.
Criteria* String The criteria of the stock query. Passing 'A' returns all stock items.
Value String Only used for some criteria, leave blank for criteria 'A'.
Back to Top

Responses

The response from the web service is a table with the specification below. If an error occurs, the response will not follow this format. Instead the response will be passed back in a single JSON string object with the parameter name: Error

Name Type Default Description
[{ "ID": "10001-123", "Description": "Test product 1", "FreeStock": 459 }] String This is the JSON returned from the fulfilment system with the amount of free stock available.
Back to Top

Errors

Below are the errors which are specific to this web service. If an error occurs the JSON returned will have with a single property called "Error". All error responses will be contained within this property.

Error Message Cause Fix
ApiKey is missing! The ApiKey parameter is missing. Pass the ApiKey in the querystring or POST form-data.
Criteria is missing! The Criteria parameter is missing. Pass the Criteria in the querystring or POST form-data.
Client record missing for client code [AccountName] The account setup has not been completed by MRM. Report the issue to us so we can advise on setup progress.
No data returned from stock availability process. An error occured when processing the query. Report the issue to us so we can investigate.
Back to Top

Available endpoints

Example requests

https://system-name.mrm.co.uk/webservices/orderplacement?ApiKey=AA11-AA11-AA11-AA11&PromoCode=[PromoCode]&OrderRecord=[OrderRecord]

Example response

{"ORDERNO": "0001234"}
Back to Top

Sample Code

    public class GetStockLevels : IHttpHandler
    {
        private class StockRecord 
	{ 
            public String ID { get; set; }
            public String Description { get; set; }
            public Int64 FreeStock { get; set; }
        }

	public class ProductVariantOption
    	{
	    public Int64 StockLevel { get; set; }
            public DateTime StockCheckDate { get; set; }
	}

	public class Product
    	{
	    public Int64 StockLevel { get; set; }
            public DateTime StockCheckDate { get; set; }
	}

        public void ProcessRequest(HttpContext context)
        {
            Boolean blnErrorOccured = false;
            Int32 intSuccessfullyUpdated = 0;
            Int32 intFailedToUpdate = 0;
            List<String> lstNotFoundProducts = new List<String>();

            String strApiKey = String.Empty;
            String strJSONResponse = String.Empty;
            String strEndpointURL = String.Empty;

            if (WebConfigurationManager.AppSettings["Newton.Enabled"] == "Yes")
            {
                strEndpointURL = WebConfigurationManager.AppSettings["Newton.GetStock.URL"];
                strApiKey = WebConfigurationManager.AppSettings["Newton.API.Key"];
            }
            else
            {
                strEndpointURL = "https://secure.mrm.co.uk/StockQueryapiHTTP.ashx";
                if (WebConfigurationManager.AppSettings["UniverseMode"] == "LIVE")
                {
                    strApiKey = WebConfigurationManager.AppSettings["LIVEFulfilmentApiKey"];
                }
                else
                {
                    strApiKey = WebConfigurationManager.AppSettings["TESTFulfilmentApiKey"];
                }
            }

            //get stock records
            using (WebClient client = new WebClient())
            {
                try
                {
                    byte[] response = client.UploadValues(strEndpointURL, new NameValueCollection()
                {
                    { "ApiKey", strApiKey },
                    { "Criteria", "A" },
                    { "Value", "" }
                });
                    strJSONResponse = Encoding.UTF8.GetString(response, 0, response.Length);
                }
                catch (Exception ex)
                {
                    strJSONResponse = ex.Message;
                    blnErrorOccured = true;
                }
            }

            if (strJSONResponse.Contains("{\"Error"))
            {
                blnErrorOccured = true;
            }
            if (String.IsNullOrWhiteSpace(strJSONResponse))
            {
                strJSONResponse = "Unable to process, blank response.";
                blnErrorOccured = true;
            }

            if (!blnErrorOccured)
            {
                //update local stock records
                using (DatabaseContext _db = new Database.Models.DatabaseContext())
                {
                    List<StockRecord> lstStockRecords = JsonConvert.DeserializeObject<List<StockRecord>>(strJSONResponse);
                    foreach (StockRecord _stockRecord in lstStockRecords)
                    {
                        Boolean blnUpdatedProduct = false;

                        //lookup item in product variants options table
                        ProductVariantOption _productVariant = _db.ProductVariantOptions.FirstOrDefault(w => w.FulfilmentCatalogueCode == _stockRecord.ID && w.Deleted == false && w.ProductVariant.Product.Deleted == false);
                        if (_productVariant != null)
                        {
                            _productVariant.StockLevel = _stockRecord.FreeStock;
                            _productVariant.StockCheckDate = DateTime.UtcNow;

                            blnUpdatedProduct = true;

                            intSuccessfullyUpdated += 1;
                        }

                        //lookup item in products table
                        Product _product = _db.Products.FirstOrDefault(w => w.FulfilmentCatalogueCode == _stockRecord.ID && w.Deleted == false);
                        if (_product != null)
                        {
                            _product.StockLevel = _stockRecord.FreeStock;
                            _product.StockCheckDate = DateTime.UtcNow;

                            blnUpdatedProduct = true;

                            intSuccessfullyUpdated += 1;
                        }

                        if (blnUpdatedProduct)
                        {
                            _db.SaveChanges();
                        }
                        else
                        {
                            //unable to find product in DB with this catalogue code.
                            intFailedToUpdate += 1;
                            lstNotFoundProducts.Add(String.Format("{0} - {1}", _stockRecord.ID, _stockRecord.Description));
                        }
                    }
                }
            }

            if (blnErrorOccured)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(String.Format("An error occured: {0}", strJSONResponse));

                //send notification email
                String strSubject = String.Format("Error occured when updating stock records from fulfilment system - {0}", WebConfigurationManager.AppSettings["SiteName"]);
                String strMessage = File.ReadAllText(context.Server.MapPath("~/EmailTemplates/") + WebConfigurationManager.AppSettings["FailedToUpdateStockRecordsFromFulfilmentEmail"]);

                //replace keywords
                strMessage = strMessage.Replace("[ErrorMessage]", strJSONResponse);

                strMessage = strMessage.Replace("[SiteName]", WebConfigurationManager.AppSettings["SiteName"]);
                strMessage = strMessage.Replace("[SiteURL]", WebConfigurationManager.AppSettings["SiteURL"]);

                SendEmail.Send(WebConfigurationManager.AppSettings["EmailFromAddress"], WebConfigurationManager.AppSettings["FulfillmentIntegrationErrorEmailAddress"], strSubject, strMessage);
                SystemLog.Add("E05", strSubject, WebConfigurationManager.AppSettings["FulfillmentIntegrationErrorEmailAddress"], (int)SiteSection.Emails);
            }
            else {
                context.Response.ContentType = "text/plain";
                context.Response.Write(String.Format("Successfully updated: {0} stock records from the fulfilment system. ", intSuccessfullyUpdated));
            
                if (intFailedToUpdate > 0)
                {
                    context.Response.Write(String.Format("{0} catalogue code(s) was not found in the webshop SQL database when attempting to update it, they are the following: {1}", intFailedToUpdate, String.Join(",", lstNotFoundProducts)));
                }
                if (intSuccessfullyUpdated == 0 && intFailedToUpdate == 0) {
                    context.Response.Write("No stockcodes to process.");
                }
            }
        }
    }
}
Back to Top