In the cart object, there are references to line items. Line items are the combination of a menu item and it's associated modifiers. There are many different combinations of menu items and modifiers that are possible when creating a cart, so we need a way to identify the menu items and modifiers as a set.
We use a deterministic hash to calculate the line_item_id using a combination of a Menu Item's ID and the IDs of it's associated Modifiers.This allows us to always ensure we're able to reconstruct the same exact id for an identical set of menu items and modifiers. This also allows us to calculate quantities by only grouping the menu item and modifier sets with the same unique deterministic hash.
We understand coming up with an algorithm that matches our format is an extra step most teams will want an easy solution for, so we'll provide two examples of the algorithm - one in JavaScript, and one in Python. Feel free to copy paste the examples below for determining what to pass as the keys in your cart object when submitting payloads to both the Price Check and Checkout endpoints. We assume the modifiers argument is a list of dicts/array of objects and the special instructions argument optional - it represents what the guest input was if allowed for that menu item.
getHashForLineItem(menuItemId, modifiers, specialInstructions) {
let stringToHash = menuItemId;
function addModifiersToHashString(modifiersToAdd) {
const sortBy = (key) => {
return (a, b) => (a[key] > b[key]) ? 1 : ((b[key] > a[key]) ? -1 : 0);
};
Array.from(modifiersToAdd)
.sort(sortBy('modifier_id'))
.forEach(modToAdd => {
stringToHash += "_" + modToAdd.modifier_id;
if(modToAdd.hasMods()){
addModifiersToHashString(modToAdd.modifiers);
}
});
}
addModifiersToHashString(modifiers);
stringToHash += specialInstructions;
const hashCode = s => s.split('').reduce((currentHash, nextChar) => {
currentHash = ((currentHash << 5) - currentHash) + nextChar.charCodeAt(0);
return currentHash & currentHash
}, 0)
return hashCode(stringToHash);
}
import hashlib
def get_hash_for_line_item(menu_item_id, modifiers, special_instructions=""):
string_to_hash = menu_item_id
def add_modifiers_to_hash_string(modifiers_to_add):
sorted_modifiers_to_add = sorted(modifiers_to_add, key=lambda m: m.modifier_id)
for mod_to_add in sorted_modifiers_to_add:
string_to_hash += ('_' + mod_to_add.modifier_id)
if mod_to_add.modifiers:
add_modifiers_to_hash_string(mod_to_add.modifiers)
add_modifiers_to_hash_string(modifiers)
string_to_hash += special_instructions
def hash_code(s):
return hashlib.md5(unicode(s).encode("utf-8")).digest().encode('base64')[:22]
return hash_code(string_to_hash)