MetabaseGetInvoices.js
1// @title Metabase Get Invoices Flow2// @description Get the invoice for the previous month from Metabase.3// @input username [string]4// @input password [string]5// @input monthLabels [array]: ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]6async function run($page, $input) {7 if (8 !Array.isArray($input.monthLabels) ||9 $input.monthLabels.length !== 12 ||10 $input.monthLabels.some(monthLabel => typeof monthLabel !== 'string' || !monthLabel.trim())11 ) {12 return $generateResponseError('monthLabels must contain the 12 month labels in calendar order');13 }14 15 const monthMap = Object.fromEntries(16 $input.monthLabels.map((monthLabel, index) => [17 monthLabel.trim().toLowerCase(),18 index + 1,19 ])20 );21 22 await $$metabase_MetabaseLogin($input.username, $input.password);23 24 async function findLinkByMonthAndYear(page, monthIndex, yearInt) {25 const rows = await page.$$('tbody > tr');26 27 for (const row of rows) {28 const tds = await row.$$('td');29 if (tds.length < 2) continue;30 31 const dateText = await (await tds[0].getProperty('innerText')).jsonValue();32 const match = dateText.trim().match(/^[a-zéû]+\s+(\d{1,2})\s+([a-zéû]+)\s+(\d{4})$/i);33 if (!match) continue;34 35 const [whole, day, monthTranslated, year] = match;36 const month = monthMap[monthTranslated.toLowerCase()];37 38 if (month === monthIndex && parseInt(year) === yearInt) {39 const link = await tds[3].$('a');40 return link;41 }42 }43 44 return null;45 }46 47 await $gotoUrl('https://store.metabase.com/account/manage/billing', 'Billing', { waitUntil: 'domcontentloaded' });48 const { year, month } = $currentDateMinusOneMonth();49 await $meta({ month, year });50 await $legend('Invoice for ' + year + '-' + month);51 await $clickElement('#mantine-r5-control-invoices-' + year);52 53 const link = await findLinkByMonthAndYear($page, parseInt(month), parseInt(year));54 55 if (!link) {56 return $generateResponseError('No invoice link found');57 }58 59 const href = await $page.evaluate(anchor => anchor.getAttribute('href'), link);60 await $gotoUrl(href, 'Invoice');61 await $clickElementAtIndex('button[type=button]', 1);62 await $sleep(3000);63 await $waitForFile();64 65 return $generateResponseSuccess('Flow completed', {66 month,67 year,68 });69}
