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
}
@olikdesign
Copy link
Author

olikdesign commented Nov 2, 2020

Dieses Widget zeigt dir die aktuelle Anzahl an Bestellungen, den Umsatz des aktuellen Monats, sowie den Jahresumsatz für deine Woocommerce Webseite.

Was wird benötigt?

  • Deine Webseiten-Url
  • Woocommerce API Key und Secret

Noch nicht umgesetzt:

  • Zurzeit werden nur die Versandkosten zur Berechnung des Nettowertes subtrahiert.
  • Caching der aktuellen Daten
  • Grafische Statistik für alle Monate (eventuell als Medium Widget)

Neu ist die Verwendung der Mehrwertsteuer in der Berechnung des monatlichen Netto-Wertes.


Ein Pfeil zeigt den derzeitigen Stand gegenüber des Vormonats.

Wer Lust hat, kann den Code gerne überarbeiten und seine Ideen mit einfließen lassen.

Widget Konfiguration

// Your website URL e.g. https://yourdomain.com
const website = "https://yourdomain.de"

  • Trage deine Webseiten Domain ein. Achte darauf, das am Ende kein "/"- Slashzeichen gesetzt wird.

// Your website name
const websiteName = "Webseite"

  • Hier kannst du deinen Webseiten Namen oder Wunschnamen eintragen, welcher im Widget ganz oben angezeigt wird.

// 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"

  • Den API Key und Secret Code erstellst du in den Woocommerce Einstellungen
    Woocommerce -> Einstellungen ->Erweitert -> REST-API
    Dort klickst du auf Schlüssel hinzufügen und kannst dem ganzen einen Namen vergeben.
    Als Berechtigung reicht "Lesen".
  • Danach muss noch "Veraltete API" aktiviert werden.
    Woocommerce -> Einstellungen ->Erweitert -> Veraltete API
    Aktivieren der alten REST-API

// Styling
const fontName = "Futura-Medium"
const bgcolor = new Color("FFBF07")
const fontColor = new Color("273540")
const mainfontColor = new Color("fff")

  • fontName ändert die Schriftart
  • bgcolor ändert die Hintergrundfarbe
  • fontColor ändert die Titel und Unterschriftenfarbe
  • mainfontColor ändert die Hauptfarbe. (Umsatzzahlen und Bestellanzahl Hintergrund)

// Calculate with Tax
var with_tax = true;

  • Aktiviere die Berechnung des Nettowertes mit Abzug der Mehrwertsteuer.
    Hier können zwei Werte angegeben werden. "true" für Ja und "false" für nein

//Currency
var currency = "\u20AC" // Euro-Sign: \u20AC

  • Um das Währungssymbol zu ändern, hast du hier die Möglichkeit.

72E9CB3A-E664-4C7A-A86F-AEFFB2E57BF2

@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