Skip to content

Instantly share code, notes, and snippets.

@olikdesign
Last active May 7, 2023 22:43
Show Gist options
  • Save olikdesign/4c9c5549686c81e728b065286eb0e750 to your computer and use it in GitHub Desktop.
Save olikdesign/4c9c5549686c81e728b065286eb0e750 to your computer and use it in GitHub Desktop.
Woocommerce Sales Widget (Current month and Year) - iOS, Scriptable
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: yellow; icon-glyph: stats;
/**
* Display Woocommerce Sales for current month
* Widget made by Oliver Kehl - www.olikdesign.de
*
* WIDGET CONFIGURATION
*/
// Your website URL e.g. https://yourdomain.com
const website = "https://yourdomain.de"
// Your website name
const websiteName = "Webseite"
// Your Woocommerce REST-API Key and Secret ( You need to enable the REST-API Settings! )
const key = "YOUR_API_KEY"
const secret = "YOUR_API_SECRET"
// Styling
const fontName = "Futura-Medium"
const bgcolor = new Color("FFBF07")
const fontColor = new Color("273540")
const mainfontColor = new Color("fff")
// Calculate with Tax
var with_tax = true;
//Currency
var currency = "\u20AC" // Euro-Sign: \u20AC
/**
* DON'T EDIT after this line
* ---------------------------------------------------------- *
*/
// Get Date formats
var date = new Date();
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var todaysdate = year + "-" + month + "-" + day
var currentYear = date.getFullYear();
var currentmonth = ("0" + (date.getMonth() + 1)).slice(-2);
var monthName = date.toLocaleString('default', { month: 'long' });
// API Folder
const folder = "reports/sales"
// Generate Api URL
const apifilter = "filter[date_min]=" + currentYear + "-01-01&filter[date_max]=" + todaysdate
const reportsUrl = website + "/wc-api/v2/" + folder + "?" + apifilter + "&consumer_key=" + key + "&consumer_secret=" + secret
const reportsRequest = new Request(reportsUrl)
const reportsData = await reportsRequest.loadJSON()
// Get Api Data
var salesreport = reportsData.sales
if (config.runsInWidget) {
// create and show widget
let widget = createWidget()
Script.setWidget(widget)
Script.complete()
}
function createWidget() {
let widget = new ListWidget()
widget.setPadding(16, 16, 16, 0)
widget.backgroundColor = bgcolor
let header = widget.addText(websiteName.toUpperCase())
header.font = Font.boldSystemFont(14)
header.textColor = fontColor
let headerSubRow = widget.addStack()
let headerSubStack = headerSubRow.addStack()
headerSubStack.layoutHorizontally()
headerSubStack.centerAlignContent()
let headersub = headerSubStack.addText("Umsatz".toUpperCase())
headersub.font = Font.regularSystemFont(12)
headersub.textColor = fontColor
headerSubStack.addSpacer(8)
widget.addSpacer()
// Get orders for current month
const salesReportTotalsEntries = Object.entries(salesreport.totals);
const salesReportTotalOrders = salesReportTotalsEntries.reduce((a, v) => {
const currentMonthOrders = v[0].split('-')[1];
if (!a[currentMonthOrders]) {
a[currentMonthOrders] = Number(v[1].orders);
return a;
}
a[currentMonthOrders] += Number(v[1].orders);
return a;
}, {});
const showcurrentMonthOrders = salesReportTotalOrders[currentmonth]
// Get sales for month
const salesReportTotalsByMonths = salesReportTotalsEntries.reduce((a, v) => {
const currentMonthSales = v[0].split('-')[1];
if (!a[currentMonthSales]) {
a[currentMonthSales] = Number(v[1].sales);
return a;
}
a[currentMonthSales] += Number(v[1].sales);
return a;
}, {});
const showcurrentMonthsales = salesReportTotalsByMonths[currentmonth]
// Get sales for current month shipping
const salesReportShippingByMonths = salesReportTotalsEntries.reduce((a, v) => {
const currentMonthSalesShipping = v[0].split('-')[1];
if (!a[currentMonthSalesShipping]) {
a[currentMonthSalesShipping] = Number(v[1].shipping);
return a;
}
a[currentMonthSalesShipping] += Number(v[1].shipping);
return a;
}, {});
const showcurrentMonthsalesShipping = salesReportShippingByMonths[currentmonth]
const showcurrentMonthsalesNet = showcurrentMonthsales - showcurrentMonthsalesShipping
const currentMonthNet = Number(Math.round(showcurrentMonthsalesNet+'e2')+'e-2')
// Get current month Tax
const salesReportTaxByMonths = salesReportTotalsEntries.reduce((a, v) => {
const currentMonthTax = v[0].split('-')[1];
if (!a[currentMonthTax]) {
a[currentMonthTax] = Number(v[1].tax);
return a;
}
a[currentMonthTax] += Number(v[1].tax);
return a;
}, {});
const showcurrentMonthTax = salesReportTaxByMonths[currentmonth]
const showcurrentMonthTaxShipNet = showcurrentMonthsales - showcurrentMonthsalesShipping - showcurrentMonthTax
const currentMonthNetTax = Number(Math.round(showcurrentMonthTaxShipNet+'e2')+'e-2')
// check if sales are more than last month
const lastmonthnumber = ("0" + (date.getMonth())).slice(-2);
const lastmonth = salesReportTotalsByMonths[lastmonthnumber]
function arrowDown() {
let arrowDownIcon = SFSymbol.named('arrow.down.right');
let arrowDownIconElement = headerSubStack.addImage(arrowDownIcon.image)
arrowDownIconElement.imageSize = new Size(10, 10)
arrowDownIconElement.tintColor = Color.red()
}
function arrowUp() {
let arrowUpIcon = SFSymbol.named('arrow.up.right');
let arrowUpIconElement = headerSubStack.addImage(arrowUpIcon.image)
arrowUpIconElement.imageSize = new Size(10, 10)
arrowUpIconElement.tintColor = Color.green()
}
// Display arrow behind subtitle
if (currentmonth > lastmonth) {
arrowUp()
} else {
arrowDown()
}
// Show current month orders quantity
let ordersRow = widget.addStack()
let ordersStack = ordersRow.addStack()
ordersStack.layoutHorizontally()
ordersStack.centerAlignContent()
ordersStack.backgroundColor = Color.white()
ordersStack.setPadding(4, 4, 4, 4)
ordersStack.cornerRadius = 4
let OrdersIcon = SFSymbol.named('tray.and.arrow.down.fill');
let OrdersIconElement = ordersStack.addImage(OrdersIcon.image)
OrdersIconElement.imageSize = new Size(12, 12)
OrdersIconElement.tintColor = fontColor
ordersStack.addSpacer(4)
let totalMonthOrders = ordersStack.addText(showcurrentMonthOrders + " Bestellung(en)")
totalMonthOrders.font = Font.mediumSystemFont(10)
totalMonthOrders.textColor = fontColor
// Show current month gross
let totalMonthGross = widget.addText(showcurrentMonthsales.toFixed(2).toString().replace(".",",") + " " + currency)
totalMonthGross.font = new Font(fontName, 25)
totalMonthGross.textColor = mainfontColor
totalMonthGross.leftAlignText()
// Generate Tax Variable
var currentMonth_tax_or_not = "";
if(with_tax) {
var currentMonth_tax_or_not = currentMonthNetTax;
} else {
var currentMonth_tax_or_not = currentMonthNet;
}
let totalMonthGrosstitle = widget.addText(monthName.toUpperCase() + " — " + currentMonth_tax_or_not.toString().replace(".",",") + " " + currency)
totalMonthGrosstitle.font = Font.boldSystemFont(9)
totalMonthGrosstitle.textColor = fontColor
// Show years total gross
let totalYearGross = widget.addText(salesreport.total_sales.replace(".",",") + " " + currency)
totalYearGross.font = new Font(fontName, 20)
totalYearGross.textColor = mainfontColor
totalYearGross.leftAlignText()
let totalYearGrosstitle = widget.addText("Jahr — ".toUpperCase() + salesreport.net_sales.replace(".",",") + " " + currency)
totalYearGrosstitle.font = Font.boldSystemFont(9)
totalYearGrosstitle.textColor = fontColor
widget.presentSmall()
return widget
}
@filip-zz
Copy link

Hi @olikdesign,
thank you for the code for scriptable dashboard. I'm trying to get the data from my WC store, but getting an error:
Error on line 85:62: TypeError: undefined is not an object (evaluating 'salesreport.totals')

Can you help me with this one?
Thanks,
Filip

@olikdesign
Copy link
Author

@filip-zz

Check your Settings:

  • Domain
  • Api Key
  • Api Secret
  • Rest Api Setting

Sounds like there is your mistake.

@Kartal0392
Copy link

Hi @olikdesign,

i have got the same error as @filip-zz. Shop-URL, Key and secret was right. Can you maybe help to fix this issue? Maybe there is an update of woocommerce and a variable can not be catched?

Thank you and best regards.
Enes

@olikdesign
Copy link
Author

@Kartal0392

the code above is working with actual version of woocommerce.

check if your Rest Api Setting is enabled in the woocommerce settings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment