public JObject deleteProductItem(JObject request) { //Get arguments request.TryGetValue("productItemID", out JToken idValue); if (idValue == null || idValue.Type != JTokenType.String) { return(Templates.MissingArguments("productItemID")); } string productID = idValue.ToString(); if (productID == "0") { return(Templates.InvalidArgument("productID")); } //Check if productItem exists ProductItem item = GetObject <ProductItem>(productID); if (item == null) { return(Templates.NoSuchProduct(productID)); } item.Delete(Connection); //Create base response return(new JObject() { { "reason", null }, }); }
public JObject updateProductItem(JObject request) { //Validate arguments string productItemID; string productID = null; request.TryGetValue("productItemID", out JToken itemIdValue); request.TryGetValue("productID", out JToken idValue); if (itemIdValue == null || itemIdValue.Type != JTokenType.String) { return(Templates.MissingArguments("productItemID")); } else { productItemID = itemIdValue.ToObject <string>(); } if (idValue != null || idValue.Type != JTokenType.String) { productID = idValue.ToObject <string>(); if (productID == "0") { return(Templates.InvalidArgument("productID")); } } //Get product, if it exists Product product = GetObject <Product>(productID); if (product == null) { return(Templates.NoSuchProduct(productID)); } //get productItem, if it exists ProductItem item = GetObject <ProductItem>(productItemID); if (item == null) { return(Templates.NoSuchProductItem(productItemID)); } //Change product ID, if necessary if (productID != null) { item.ProductId = productID; } item.Update(Connection); //Create response return(new JObject() { { "reason", null }, }); }
public JObject addProductItem(JObject request) { //Get arguments string productID; int count; request.TryGetValue("productID", out JToken productIDValue); request.TryGetValue("count", out JToken countValue); if (productIDValue == null || productIDValue.Type != JTokenType.String) { return(Templates.MissingArguments("productID")); } else { productID = productIDValue.ToObject <string>(); } if (countValue == null || countValue.Type != JTokenType.Integer) { count = 1; } else { count = countValue.ToObject <int>(); if (count > 30) { return(Templates.InvalidArgument("count")); } } //Check if product exists Product product = GetObject <Product>(productID); if (product == null) { return(Templates.NoSuchProduct(productID)); } //Create productItems List <int> IDs = new List <int>(); for (int i = count; i != 0; i--) { ProductItem item = new ProductItem(null, productID); item.Upload(Connection); IDs.Add(item.Id.Value); } //Create response return(new JObject() { { "reason", null }, { "responseData", new JArray(IDs) } }); }
public JObject getProductItems(JObject request) { // Get request arguments request.TryGetValue("products", out JToken requestProductIds); request.TryGetValue("itemIds", out JToken requestItemIds); // Verify the presence of at least one argument if (requestProductIds == null && requestItemIds == null) { return(Templates.MissingArguments("products", "itemIds")); } // Verify the argument if (requestProductIds != null && (requestProductIds.Type != JTokenType.Array || requestProductIds.Any(x => x.Type != JTokenType.String))) { return(Templates.InvalidArgument("products")); } if (requestItemIds != null && (requestItemIds.Type != JTokenType.Array || requestItemIds.Any(x => x.Type != JTokenType.Integer))) { return(Templates.InvalidArgument("itemIds")); } //Create base response var responseData = new JObject(); JObject response = new JObject() { { "reason", null }, { "responseData", responseData } }; // Prepare values requestProductIds = requestProductIds ?? new JArray(); requestItemIds = requestItemIds ?? new JArray(); // Request ProductItem data from database ILookup <string, ProductItem> productItemData = Core_getProductItems(requestProductIds.ToObject <string[]>(), requestItemIds.ToObject <int[]>()); // Add all grouped productItems as dictionaries to responseData foreach (var data in productItemData) { // Creates an array with the key of the productId, containing all associated items var items = new JArray(); foreach (var productItem in data) { items.Add(productItem.Id); } responseData[data.Key] = items; } return(response); }
/// <summary> /// Gets the user info from the request and sets the <see cref="CurrentUser"/> value. /// If <see cref="CurrentUser"/> is already set, this function does nothing. /// </summary> /// <remarks> /// In case this returns false, the response value must be returned to the client. /// </remarks> /// <param name="request">The request from whom to take the user info.</param> /// <param name="response">A response JObject. In case of an error, this will be an error JSON. Otherwise always null.</param> /// <returns>True if no errors were encountered. Otherwise false.</returns> private bool GetUser(JObject request, out JObject response) { // Prevent redundant calls if (CurrentUser != null) { response = null; return(true); } request.TryGetValue("username", out JToken username); request.TryGetValue("token", out JToken token); // Verify arguments var missing = new List <string>(); if (username == null) { missing.Add("username"); } if (token == null) { missing.Add("token"); } if (missing.Any()) { response = Templates.MissingArguments(missing.ToArray()); return(false); } // If the token can't be parsed, respond with 'InvalidArgument' if (!long.TryParse(token.ToString(), out long _)) { response = Templates.InvalidArgument("token"); return(false); } // Get user, or if no user was found, respond with "InvalidLogin" CurrentUser = GetObject <User>(username, "username"); if (CurrentUser == null) { response = Templates.InvalidLogin; return(false); } // Verification succeeded response = null; return(true); }
public JObject deleteLoan(JObject request) { // Get arguments request.TryGetValue("loanId", out JToken loanId); // Verify arguments if (loanId == null || loanId.Type != JTokenType.Integer) { return(Templates.InvalidArgument("loanId")); } // Build condition var condition = new MySqlConditionBuilder(); if (CurrentUser.Permission <= UserPermission.User) { condition.Column("user").Equals(CurrentUser.Username, MySqlDbType.String); } condition.And().Column("id").Equals(loanId, MySqlDbType.String); // Get and delete loan, or return error if no such loan exists var loan = Connection.Select <LoanItem>(condition, range: (0, 1)).FirstOrDefault(); if (loan == null) { return(Templates.NoSuchLoan(loanId.ToString())); } if (loan.Start < DateTime.Now) { return(Templates.LoanAlreadyStarted()); } Connection.Delete(loan); // Create response JObject response = new JObject() { { "reason", null } }; return(response); }
public JObject resizeLoan(JObject request) { //Get arguments request.TryGetValue("loanId", out JToken loanItemID); request.TryGetValue("start", out JToken requestStart); request.TryGetValue("end", out JToken requestEnd); // Verify the arguments List <string> failedVerifications = new List <string>(); if (loanItemID == null || loanItemID.Type != JTokenType.Integer) { failedVerifications.Add("loanId"); } if (requestStart == null || !(requestStart.Type == JTokenType.String || requestStart.Type == JTokenType.Date)) { failedVerifications.Add("start"); } if (requestEnd == null || !(requestEnd.Type == JTokenType.String || requestEnd.Type == JTokenType.Date)) { failedVerifications.Add("end"); } if (failedVerifications.Any()) { return(Templates.InvalidArguments(failedVerifications.ToArray())); } // Parse arguments DateTime start; DateTime end; string loanID = loanItemID.ToString(); try { start = DateTime.Parse(requestStart.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'start'")); } try { end = DateTime.Parse(requestEnd.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'end'")); } if (end < start) { return(Templates.InvalidArguments("'end' must come after 'start'")); } DateTimeSpan newLoanSpan = new DateTimeSpan(start, end); if (newLoanSpan.Start < DateTime.Now.Date) { return(Templates.InvalidArgument("'start' may not be set earlier than today.")); } if (newLoanSpan.Duration > MaxLoanDuration) { return(Templates.InvalidArgument($"Duration of the loan may not exceed {MaxLoanDuration.Days} days.")); } // Build a condition to get the specific loan var condition = new MySqlConditionBuilder(); // Automatically limit results to current user only if their permission is User if (CurrentUser.Permission <= UserPermission.User) { condition.And().Column("user").Equals(CurrentUser.Username, MySqlDbType.String); } condition.And().Column("id").Equals(loanID, MySqlDbType.Int32); //Get the specified loanItem if it exists. If it doesn't, throw an error. LoanItem oldLoan = Connection.Select <LoanItem>(condition).FirstOrDefault(); if (oldLoan == null) { return(Templates.NoSuchLoan(loanID)); } // Return a loanExpired template if the loan has already ended if (oldLoan.End < DateTime.Now) { return(Templates.LoanExpired()); } if (oldLoan.Start < DateTime.Now && oldLoan.Start != start) { return(Templates.LoanAlreadyStarted()); } // Build condition condition = new MySqlConditionBuilder() .Column("product_item") .Equals(oldLoan.ProductItem, MySqlDbType.Int32); // Select only relevant loans condition.And().Column("end").GreaterThanOrEqual().Operand(start, MySqlDbType.DateTime); condition.And().Column("start").LessThanOrEqual().Operand(end, MySqlDbType.DateTime); //Get all loanItems for this loan's product_item. var loans = Connection.Select <LoanItem>(condition).ToList(); //Check for conflicting loanItems bool canResize = true; foreach (var loan in loans) { var loanSpan = new DateTimeSpan(loan.Start, loan.End); if (newLoanSpan.Overlaps(loanSpan)) { canResize = false; break; } } //Create response var responseData = new JObject(); JObject response = new JObject() { { "reason", null }, { "responseData", responseData } }; if (canResize) { // Update loan oldLoan.Start = start; oldLoan.End = end; Connection.Update(oldLoan); } else if (oldLoan.IsAcquired && !canResize) // If loan is not eligible for a item reassignment { return(Templates.LoanResizeFailed()); } else // If the loan is eligible for an item reassignment { // Try to retrieve a list of unreserved equivalent products var unreservedAlts = Core_GetUnreservedItems(oldLoan.GetProductItem(Connection).ProductId, newLoanSpan); if (unreservedAlts == null) // Normally this value should not be able to be null. This block is just a failsafe that adds context. { throw new InvalidOperationException("Expected type of 'unreservedAlts' is List, but nullreference was found."); } if (!unreservedAlts.Any()) { Log.Error("Failed at line 107"); return(Templates.LoanResizeFailed()); } // Update loan oldLoan.ProductItem = unreservedAlts.First().Id.Value; oldLoan.Start = start; oldLoan.End = end; Connection.Update(oldLoan); // Return new data in response and add message for context responseData["product_item"] = oldLoan.ProductItem; response["message"] = "Loan has been reassigned."; } return(response); }
public JObject getLoans(JObject request) { // Get arguments request.TryGetValue("columns", out JToken requestColumns); request.TryGetValue("productItemIds", out JToken requestProductItems); request.TryGetValue("userId", out JToken requestUserId); request.TryGetValue("loanItemID", out JToken requestLoanId); request.TryGetValue("start", out JToken requestStart); request.TryGetValue("end", out JToken requestEnd); // Verify arguments List <string> failedVerifications = new List <string>(); if (requestColumns != null && (requestColumns.Type != JTokenType.Array || requestColumns.Any(x => x.Type != JTokenType.String))) { failedVerifications.Add("columns"); } if (requestProductItems != null && (requestProductItems.Type != JTokenType.Array || requestProductItems.Any(x => x.Type != JTokenType.String))) { failedVerifications.Add("productItemIds"); } if (requestUserId != null && requestUserId.Type != JTokenType.String) { failedVerifications.Add("userId"); } if (failedVerifications.Any()) { return(Templates.InvalidArguments(failedVerifications.ToArray())); } // Parse arguments DateTime start; DateTime end; try { start = requestStart == null ? new DateTime() : DateTime.Parse(requestStart.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'start'")); } try { end = requestEnd == null ? new DateTime() : DateTime.Parse(requestEnd.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'end'")); } // Prepare values if (requestColumns == null || requestColumns.Count() == 0) { requestColumns = new JArray(LoanItem.metadata.Select(x => x.Column)); } // Build condition var condition = new MySqlConditionBuilder(); if (requestProductItems != null && requestProductItems.Any()) { condition.NewGroup(); foreach (var productItem in requestProductItems) { condition.Or() .Column("product_item") .Equals(productItem, MySqlDbType.String); } condition.EndGroup(); } // Filter by specific loan id if (requestLoanId != null) { condition.And().Column("id").Equals(requestLoanId, MySqlDbType.Int32); } // Filter by user if (requestUserId != null) { condition.And().Column("user").Equals(requestUserId, MySqlDbType.String); } // Automatically limit results to current user only if their permission is User if (CurrentUser.Permission <= UserPermission.User) { condition.And().Column("user").Equals(CurrentUser.Username, MySqlDbType.String); } // Select only relevant loans if (requestStart != null) { condition.And().Column("end").GreaterThanOrEqual().Operand(start, MySqlDbType.DateTime); } if (requestEnd != null) { condition.And().Column("start").LessThanOrEqual().Operand(end, MySqlDbType.DateTime); } // Get loans var loans = Connection.Select <LoanItem>(requestColumns.ToObject <string[]>(), condition); // Build base response var responseData = new JArray(); JObject response = new JObject() { { "reason", null }, { "responseData", responseData } }; // Populate responseData foreach (var loanData in loans) { var item = new JObject(); for (int i = 0; i < requestColumns.Count(); i++) { if (loanData[i] is DateTime) { item[(string)requestColumns[i]] = new JValue(((DateTime)loanData[i]).ToUniversalTime().Subtract(Epoch).TotalMilliseconds); } else { item[(string)requestColumns[i]] = new JValue(loanData[i]); } } responseData.Add(item); } return(response); }
public JObject updateProduct(JObject request) { //Validate arguments string productID; string newProductID = null; string categoryID = null; string manufacturer = null; string extension = null; byte[] imageData = null; JObject names = null; JObject descriptions = null; JObject newImage = null; request.TryGetValue("productID", out JToken idValue); request.TryGetValue("newProductID", out JToken newIDValue); request.TryGetValue("categoryID", out JToken categoryIDValue); request.TryGetValue("manufacturer", out JToken manufacturerValue); request.TryGetValue("name", out JToken nameValue); request.TryGetValue("description", out JToken descriptionValue); request.TryGetValue("image", out JToken imageValue); if (idValue == null || idValue.Type != JTokenType.String) { return(Templates.MissingArguments("productID")); } else { productID = idValue.ToObject <string>(); if (productID == "default") { return(Templates.InvalidArgument("categoryID")); } } if (newIDValue != null && newIDValue.Type == JTokenType.String) { newProductID = newIDValue.ToObject <string>(); } if (categoryIDValue != null && categoryIDValue.Type == JTokenType.String) { categoryID = categoryIDValue.ToObject <string>(); } if (manufacturerValue != null && manufacturerValue.Type == JTokenType.String) { manufacturer = manufacturerValue.ToObject <string>(); } if (nameValue != null && nameValue.Type == JTokenType.Object) { names = nameValue.ToObject <JObject>(); } if (descriptionValue != null && descriptionValue.Type == JTokenType.Object) { descriptions = descriptionValue.ToObject <JObject>(); } if (imageValue != null && imageValue.Type == JTokenType.Object) { newImage = imageValue.ToObject <JObject>(); newImage.TryGetValue("data", out JToken dataValue); newImage.TryGetValue("extension", out JToken extensionValue); if (extensionValue != null && extensionValue.Type == JTokenType.String) { extension = extensionValue.ToObject <string>(); if (!Image.ImageFormats.Contains(extension)) { return(Templates.InvalidArgument("extension")); } } if (dataValue != null && dataValue.Type == JTokenType.String) { imageData = (byte[])dataValue; } } //Get product, if it exists Product product = GetObject <Product>(productID); if (product == null) { return(Templates.NoSuchProduct(productID)); } //If a new ID was given, check if it exists first. Product newProduct = GetObject <Product>(newProductID); if (newProduct != null) { return(Templates.AlreadyExists(productID)); } ///////////////Image //Edit image if needed; Image image = product.GetImage(Connection); if (newImage != null) { string oldID = image.Id; if (image.Id == "default") { image = new Image(product.Id + "_image", image.Data, image.Extension); } if (extension != null) { image.Extension = extension; } if (imageData != null) { image.Data = imageData; } if (oldID != image.Id) { image.Upload(Connection); product.UpdateTrace(); product.Image = image.Id; product.Update(Connection); } else { image.Update(Connection); } } ///////////////Name //Edit the LanguageItem if needed; LanguageItem name = product.GetName(Connection); if (names != null) { if (names.TryGetValue("en", out JToken enValue)) { if (enValue.Type == JTokenType.String) { name.en = enValue.ToObject <string>(); } } if (names.TryGetValue("nl", out JToken nlValue)) { if (nlValue.Type == JTokenType.String) { name.nl = nlValue.ToObject <string>(); } } if (names.TryGetValue("ar", out JToken arValue)) { if (arValue.Type == JTokenType.String) { name.ar = arValue.ToObject <string>(); } } name.Update(Connection); } ///////////////Description //Edit the LanguageItem if needed; LanguageItem description = product.GetDescription(Connection); if (descriptions != null) { if (descriptions.TryGetValue("en", out JToken enValue)) { if (enValue.Type == JTokenType.String) { description.en = enValue.ToObject <string>(); } } if (descriptions.TryGetValue("nl", out JToken nlValue)) { if (nlValue.Type == JTokenType.String) { description.nl = nlValue.ToObject <string>(); } } if (descriptions.TryGetValue("ar", out JToken arValue)) { if (arValue.Type == JTokenType.String) { description.ar = arValue.ToObject <string>(); } } description.Update(Connection); } //If a new ID was specified, change the product ID. if (newProductID != null) { image.Id = newProductID + "_image"; image.Update(Connection); product.Image = image.Id; name.Id = newProductID + "_name"; name.Update(Connection); description.Id = newProductID + "_description"; description.Update(Connection); product.Name = name.Id; product.UpdateTrace(); product.Id = newProductID; } ///////////////Product //If a new category was specified, check if it exists. If it does, change the product category if (categoryID != null) { ProductCategory category = GetObject <ProductCategory>(categoryID); if (category == null) { return(Templates.NoSuchProductCategory(categoryID)); } else { product.Category = categoryID; } } //If a new manufacturer was specified, change it. if (manufacturer != null) { product.Manufacturer = manufacturer; } product.Update(Connection); //Create response return(new JObject() { { "reason", null }, { "success", true } }); }
public JObject addLoan(JObject request) { //Get arguments request.TryGetValue("productId", out JToken requestProductId); request.TryGetValue("start", out JToken requestStart); request.TryGetValue("end", out JToken requestEnd); // Verify the arguments List <string> failedVerifications = new List <string>(); if (requestProductId == null || requestProductId.Type != JTokenType.String) { failedVerifications.Add("productID"); } if (requestStart == null || !(requestStart.Type == JTokenType.String || requestStart.Type == JTokenType.Date)) { failedVerifications.Add("start"); } if (requestEnd == null || !(requestEnd.Type == JTokenType.String || requestEnd.Type == JTokenType.Date)) { failedVerifications.Add("end"); } if (failedVerifications.Any()) { return(Templates.InvalidArguments(failedVerifications.ToArray())); } // Parse arguments DateTime start; DateTime end; string productId = requestProductId.ToString(); try { start = DateTime.Parse(requestStart.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'start'")); } try { end = DateTime.Parse(requestEnd.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'end'")); } if (end < start) { return(Templates.InvalidArguments("'end' must come after 'start'")); } var newLoanSpan = new DateTimeSpan(start, end); if (newLoanSpan.Start < DateTime.Now.Date) { return(Templates.InvalidArgument("'start' may not be set earlier than today.")); } if (newLoanSpan.Duration > MaxLoanDuration) { return(Templates.InvalidArgument($"Duration of the loan may not exceed {MaxLoanDuration.Days} days.")); } // Get an unreserved product item ProductItem item; try { item = Core_GetUnreservedItems(productId, newLoanSpan).FirstOrDefault(); } catch (Exception) { return(Templates.NoItemsForProduct(productId)); } if (item == null) { return(Templates.NoItemsForProduct($"Product '{productId}' has no items available during this time.")); } var loan = new LoanItem(null, CurrentUser.Username, item.Id.Value, start, end); Connection.Upload(loan); //Create response JObject response = new JObject() { { "reason", null }, { "responseData", new JObject() { { "loanId", loan.Id }, { "productItem", item.Id } } } }; return(response); }
public JObject addProductCategory(JObject request) { //Get arguments string categoryID; request.TryGetValue("categoryID", out JToken categoryIDValue); request.TryGetValue("name", out JToken nameValue); if (categoryIDValue == null || categoryIDValue.Type != JTokenType.String || nameValue == null || nameValue.Type != JTokenType.Object ) { return(Templates.MissingArguments("categoryID, name")); } else { categoryID = categoryIDValue.ToObject <string>(); if (categoryID == "default" || categoryID == "uncategorized") { return(Templates.InvalidArgument("categoryID")); } } //Get languages string en; string nl = null; string ar = null; JObject names = nameValue.ToObject <JObject>(); names.TryGetValue("en", out JToken enValue); names.TryGetValue("nl", out JToken nlValue); names.TryGetValue("ar", out JToken arValue); if (enValue != null && enValue.Type == JTokenType.String) { en = names["en"].ToObject <string>(); } else { return(Templates.MissingArguments("en")); } if (nlValue != null && nlValue.Type == JTokenType.String) { nl = names["nl"].ToObject <string>(); } if (arValue != null && arValue.Type == JTokenType.String) { ar = names["ar"].ToObject <string>(); } //Check if category already exists ProductCategory category = GetObject <ProductCategory>(categoryID); if (category != null) { return(Templates.AlreadyExists(categoryID)); } //Create category, languageitem LanguageItem item = new LanguageItem(categoryID + "_name", en, nl, ar); item.Upload(Connection); category = new ProductCategory(categoryID, item.Id); category.Upload(Connection); //Create response return(new JObject() { { "reason", null }, { "success", true } }); }
public JObject addProduct(JObject request) { //Get arguments string productID; string manufacturer; string categoryID; request.TryGetValue("productID", out JToken productIDValue); request.TryGetValue("categoryID", out JToken categoryIDValue); request.TryGetValue("manufacturer", out JToken manufacturerValue); request.TryGetValue("description", out JToken descriptionValue); request.TryGetValue("name", out JToken nameValue); // Verify presence of arguments List <string> failedVerifications = new List <string>(); if (productIDValue == null) { failedVerifications.Add("productID"); } if (categoryIDValue == null) { failedVerifications.Add("categoryID"); } if (manufacturerValue == null) { failedVerifications.Add("manufacturer"); } if (nameValue == null) { failedVerifications.Add("name"); } if (failedVerifications.Any()) { return(Templates.MissingArguments(failedVerifications.ToArray())); } // Verify arguments if (productIDValue.Type != JTokenType.String) { failedVerifications.Add("productID"); } if (categoryIDValue.Type != JTokenType.String) { failedVerifications.Add("categoryID"); } if (manufacturerValue.Type != JTokenType.String) { failedVerifications.Add("manufacturer"); } if (nameValue.Type != JTokenType.Object) { failedVerifications.Add("name"); } if (failedVerifications.Any()) { return(Templates.InvalidArguments(failedVerifications.ToArray())); } // Prepare values productID = productIDValue.ToObject <string>(); manufacturer = manufacturerValue.ToObject <string>(); categoryID = categoryIDValue.ToObject <string>(); // Get image request.TryGetValue("image", out JToken imageValue); string extension = null; byte[] imageData = null; if (imageValue != null && imageValue.Type == JTokenType.Object) { JObject image = imageValue.ToObject <JObject>(); image.TryGetValue("data", out JToken dataValue); image.TryGetValue("extension", out JToken extensionValue); if (extensionValue != null && extensionValue.Type == JTokenType.String && dataValue != null && dataValue.Type == JTokenType.String) { extension = extensionValue.ToObject <string>(); imageData = (byte[])dataValue; if (!Image.ImageFormats.Contains(extension)) { return(Templates.InvalidArgument("extension")); } } else { return(Templates.MissingArguments("data, extension")); } } // Get languages string en; string nl = null; string ar = null; JObject names = nameValue.ToObject <JObject>(); names.TryGetValue("en", out JToken nameEnValue); names.TryGetValue("nl", out JToken nameNlValue); names.TryGetValue("ar", out JToken nameArValue); if (nameEnValue != null && nameEnValue.Type == JTokenType.String) { en = names["en"].ToObject <string>(); } else { return(Templates.MissingArguments("name: en")); } if (nameNlValue != null && nameNlValue.Type == JTokenType.String) { nl = names["nl"].ToObject <string>(); } if (nameArValue != null && nameArValue.Type == JTokenType.String) { ar = names["ar"].ToObject <string>(); } LanguageItem name = new LanguageItem(productID + "_name", en, nl, ar); LanguageItem description; if (descriptionValue != null && descriptionValue.Type == JTokenType.Object) { //Get description JObject desc = descriptionValue.ToObject <JObject>(); desc.TryGetValue("en", out JToken descEnValue); desc.TryGetValue("nl", out JToken descNlValue); desc.TryGetValue("ar", out JToken descArValue); if (descEnValue != null && descEnValue.Type == JTokenType.String) { en = desc["en"].ToObject <string>(); } else { return(Templates.MissingArguments("description: en")); } if (descNlValue != null && descNlValue.Type == JTokenType.String) { nl = desc["nl"].ToObject <string>(); } if (descArValue != null && descArValue.Type == JTokenType.String) { ar = desc["ar"].ToObject <string>(); } description = new LanguageItem(productID + "_description", en, nl, ar); } else { description = new LanguageItem(productID + "_description", null); } //Check if product already exists Product product = GetObject <Product>(productID); if (product != null) { return(Templates.AlreadyExists(productID)); } //Check if category exists ProductCategory category = GetObject <ProductCategory>(categoryID); if (category == null) { return(Templates.NoSuchProductCategory(categoryID)); } //Create product, languageItem, image name.Upload(Connection); description.Upload(Connection); if (imageData != null) { Image image = new Image(productID + "_image", imageData, extension); image.Upload(Connection); product = new Product(productID, manufacturer, categoryID, productID + "_name", productID + "_description", image.Id); } else { product = new Product(productID, manufacturer, categoryID, productID + "_name", productID + "_description"); } product.Upload(Connection); //Create response return(new JObject() { { "reason", null }, }); }
public JObject getUnavailableDates(JObject request) { // Get arguments request.TryGetValue("productId", out JToken requestProductId); request.TryGetValue("start", out JToken requestStart); request.TryGetValue("end", out JToken requestEnd); // Verify arguments List <string> failedVerifications = new List <string>(); if (requestProductId == null || requestProductId.Type != JTokenType.String) { return(Templates.InvalidArgument("productId")); } if (requestStart == null) { return(Templates.InvalidArgument("start")); } if (requestEnd == null) { return(Templates.InvalidArgument("end")); } if (failedVerifications.Any()) { return(Templates.InvalidArguments(failedVerifications.ToArray())); } // Parse arguments DateTime start; DateTime end; try { start = requestStart == null ? new DateTime() : DateTime.Parse(requestStart.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'start'")); } try { end = requestEnd == null ? new DateTime() : DateTime.Parse(requestEnd.ToString()); } catch (Exception) { return(Templates.InvalidArgument("Unable to parse 'end'")); } var range = new DateTimeSpan(start, end); if (range.Duration.Days > 122) { return(Templates.InvalidArgument("start and end may not be more than 122 days apart.")); } // Get all items var condition = new MySqlConditionBuilder("product", MySqlDbType.String, requestProductId.ToString()); var productItems = Connection.Select <ProductItem>(condition).ToArray(); // Return empty response if no items were found if (!productItems.Any()) { return new JObject() { { "reason", null }, { "responseData", new JArray() } } } ; // Get all loans within the specified range condition = new MySqlConditionBuilder("product_item", MySqlDbType.Int32, productItems.Select(x => x.Id).Cast <object>().ToArray()); condition.And() .Column("end") .GreaterThanOrEqual() .Operand(range.Start, MySqlDbType.DateTime); condition.And() .Column("start") .LessThanOrEqual() .Operand(range.End, MySqlDbType.DateTime); var loanItems = Connection.Select <LoanItem>(condition).ToArray(); // No idea if this is the most efficient way, but it basically iterates // through all dates of a loan and slaps them in a cache. If the cache // already contains the date, it increases the counter. // If the counter is larger or equal to the total amount of items, we // consider that date unavailable. var dateCache = new Dictionary <DateTime, int>(); foreach (var loan in loanItems) { while (loan.Start < loan.End) { if (loan.Start < range.Start) { loan.Start = loan.Start.AddDays(1); continue; } if (loan.End > range.End) { break; } if (dateCache.ContainsKey(loan.Start)) { dateCache[loan.Start]++; } else { dateCache[loan.Start] = 1; } loan.Start = loan.Start.AddDays(1); } } // Build base response var responseData = new JArray(); JObject response = new JObject() { { "reason", null }, { "responseData", responseData } }; // Add all dates with an amount of loans greater or equal to the max available items foreach ((DateTime date, int count) in dateCache) { if (count >= productItems.Length) { responseData.Add((long)(date.ToUniversalTime() - Epoch).TotalMilliseconds); } } return(response); } }
public JObject updateProductCategory(JObject request) { //Validate arguments string categoryID; string newCategoryID = null; JObject names = null; request.TryGetValue("categoryID", out JToken categoryIDValue); request.TryGetValue("newCategoryID", out JToken newCategoryIDValue); request.TryGetValue("name", out JToken nameValue); if (categoryIDValue == null || categoryIDValue.Type != JTokenType.String) { return(Templates.MissingArguments("categoryID")); } else { categoryID = categoryIDValue.ToObject <string>(); if (categoryID == "default" || categoryID == "uncategorized") { return(Templates.InvalidArgument("categoryID")); } } if (newCategoryIDValue != null && newCategoryIDValue.Type == JTokenType.String) { newCategoryID = newCategoryIDValue.ToObject <string>(); } if (nameValue != null && nameValue.Type == JTokenType.Object) { names = nameValue.ToObject <JObject>(); } //Get product, if it exists ProductCategory category = GetObject <ProductCategory>(categoryID); if (category == null) { return(Templates.NoSuchProductCategory(categoryID)); } ///////////////LanguageItem //Edit the LanguageItem if needed; LanguageItem item = category.GetName(Connection); if (names != null) { if (names.TryGetValue("en", out JToken enValue)) { if (enValue.Type == JTokenType.String) { item.en = enValue.ToObject <string>(); } } if (names.TryGetValue("nl", out JToken nlValue)) { if (nlValue.Type == JTokenType.String) { item.nl = nlValue.ToObject <string>(); } } if (names.TryGetValue("ar", out JToken arValue)) { if (arValue.Type == JTokenType.String) { item.ar = arValue.ToObject <string>(); } } item.Update(Connection); } //If a new product ID was specified, check if it already exists. If it doesn't, change the product ID. if (newCategoryID != null) { ProductCategory newProduct = GetObject <ProductCategory>(newCategoryID); if (newProduct != null) { return(Templates.AlreadyExists(categoryID)); } else { item.Id = newCategoryID + "_name"; item.Update(Connection); category.Name = item.Id; category.UpdateTrace(); category.Id = newCategoryID; } } category.Update(Connection); //Create response return(new JObject() { { "reason", null }, { "success", true } }); }