Custom pricing module
Weather-dependent barbeque sausage pricing
Usually when summer kicks in in Switzerland and people start to invite friends to the first barbeque party of the year, demand for sausages surges instantly. Our dear friend, butcher Bruno wants to sell his homemade sausages directly to the customer with his online shop and had this crazy idea of a special product pricing he calls weather-dependent barbeque sausage pricing.
Add a pricing module
To demonstrate, we will implement an ingenious pricing that increases the catalog price by 1 USD if the temperature reaches 20 degrees celsius in Zürich:
import { ProductPricingDirector, ProductPricingAdapter } from "meteor/unchained:core-pricing";
import fetch from "isomorphic-unfetch";
const PRODUCT_TAG_SAUSAGE = "sausage";
const SAUSAGE_THRESHOLD_CELSIUS = 20;
class WeatherDependentBarbequeSausagePricing extends ProductPricingAdapter {
static key = "shop.unchained.wd-bbq-sausage-pricing";
static version = "1.0";
static label = "Calculate the price of a sausage 🌭🌦";
static orderIndex = 3;
static isActivatedFor({product}) {
if (
product.tags &&
product.tags.length > 0 &&
product.tags.indexOf(PRODUCT_TAG_SAUSAGE) !== -1
) {
return true;
}
return false;
}
async calculate() {
const { currency, quantity } = this.context;
try {
const response = await fetch(
"https://community-open-weather-map.p.rapidapi.com/weather?q=zurich,ch&units=metric",
{
headers: {
"x-rapidapi-key": "2a849e288dmsh59370f28a9102f6p1c881cjsn28010ce8ff58",
"x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
"useQueryString": true
}
}
);
if (response.status === 200) {
const { main } = await response.json();
const { temp} = main;
if (temp) {
if (temp > SAUSAGE_THRESHOLD_CELSIUS) {
console.log("🌭 -> High season, sausage pricy!!");
this.result.addItem({
currency,
amount: 100 * quantity,
isTaxable: true,
isNetPrice: true,
meta: { adapter: this.constructor.key }
});
}
}
}
} catch (e) {
console.error('🌭 -> Failed while trying to price weather dependent');
}
return super.calculate();
}
}
ProductPricingDirector.registerAdapter(WeatherDependentBarbequeSausagePricing);
Craft the query
Unchained Commerce is headless by design. So in order to get the product data from our Unchained Engine, we need to craft a small GraphQL query that actually resolves some texts and the current price of our sausage.
query getProduct {
product(slug: "🌭") {
_id
texts {
title
}
... on SimpleProduct {
catalogPrice {
price {
amount
currency
}
}
}
}
}
Build the UI
Because Unchained Commerce is headless, you can build any UI on any operating system that can somehow connect to the HTTP endpoint. How awesome is that?