Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 01 of 30 · Pathway 1 — Spreadsheet Automation

Automated Sales Dashboard

Manual regional totals are slow and error-prone. Aggregate revenue by region.

Real-world benefit
Small shops, course sales and department reporting.
Technologies
Google Sheets, SpreadsheetApp, Charts, Custom menu
Required knowledge
None. Knowing what a spreadsheet row and column are is enough.
Time and level
About 20 minutes · Beginner
AI requirement
None: deterministic Apps Script
Expected baseline
East 160; West 100; total 260.

Loading the interactive studio…

Introduction

The totals object accumulates units times price per region; reduce computes the grand total; the chart excludes the total row. The application's entry point is buildDashboard(). Baseline limitation, as stated in the workshop: No date filter or product breakdown yet.

Key building blocks: getValues(); Map or reduce(); setValues(); newChart().

Practical use cases

Small shops, course sales and department reporting.

Prerequisites

  • None. Knowing what a spreadsheet row and column are is enough.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "Sales" (fictional)
DateRegionProductUnitsUnit price
2026-11-01EastCourse340
2026-11-02WestBook520
2026-11-03EastBook220

Setup in your own Google account

  1. Download 01-automated-sales-dashboard.zip (Code.gs, starter.csv, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Sales, then File → Import → Upload starter.csv → Replace current sheet.
  4. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  5. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  6. Check the result: East 160; West 100; total 260.

Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.

Complete source code (Code.gs)

From 01-automated-sales-dashboard at commit 4a26d919, SHA-256 5bc144b0719f. Unchanged.

// Automated Sales Dashboard
// Entry point: buildDashboard; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","buildDashboard").addToUi();}
function buildDashboard(){
// Aggregate revenue by region, then replace the previous chart.
const totals={}; input('Sales').forEach(r=>{totals[r[1]]=(totals[r[1]]||0)+num(r[3])*num(r[4]);}); const rows=Object.entries(totals); const s=output('Dashboard',['Region','Revenue'],[...rows,['Total',rows.reduce((a,r)=>a+r[1],0)]]); s.getCharts().forEach(c=>s.removeChart(c)); if(rows.length)s.insertChart(s.newChart().setChartType(Charts.ChartType.COLUMN).addRange(s.getRange(1,1,rows.length+1,2)).setPosition(2,4,0,0).build());
}
function input(name) { const s=SpreadsheetApp.getActive().getSheetByName(name); if(!s) throw Error('Missing tab: '+name); return s.getDataRange().getValues().slice(1).filter(r=>r.some(v=>v!=='')); }
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
function num(v){if(v===''||!Number.isFinite(Number(v))) throw Error('Invalid number: '+v); return Number(v);}

How the code works

Beginner explanation

buildDashboard() reads every sales row, multiplies units by price and adds the result to a running total for that row's region. It then writes one row per region plus a Total row to a Dashboard tab and draws a column chart.

Technical explanation

totals is a plain object used as a map keyed by region (r[1]). input() returns non-blank data rows without the header; num() validates and converts cells. Object.entries() turns the map into [region, revenue] rows, reduce() sums the grand total, and output() clears and rewrites the Dashboard in one batch setValues() call. Existing charts are removed before inserting a new one so reruns do not stack charts; the chart range excludes the Total row.

Slide excerpt

This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.

function buildDashboard(){
// Aggregate revenue by region, then replace the previous chart.
const totals={}; input('Sales').forEach(r=>{totals[r[1]]=(totals[r[1]]||0)+num(r[3])*num(r[4]);}); const rows=Object.entries(totals); const s=output('Dashboard',['Region','Revenue'],[...rows,['Total',rows.reduce((a,r)=>a+r[1],0)]]); s.getCharts().forEach(c=>s.removeChart(c)); if(rows.length)s.insertChart(s.newChart().setChartType(Charts.ChartType.COLUMN).addRange(s.getRange(1,1,rows.length+1,2)).setPosition(2,4,0,0).build());
}

Common mistakes

  • Including the Total row in the chart range, which makes one bar dwarf the others.
  • Reading cells one at a time with getValue() inside a loop instead of one getValues() call.
  • Forgetting to remove the previous chart, so every run adds another chart.

Run it and expected output

Choose Workshop → Run application (runs buildDashboard()). Expected: East 160; West 100; total 260.

Original workshop exercise

Change East Course units from 3 to 4; total becomes 300.

Troubleshooting and debugging

A price typed as words

Someone typed the West Book price as the word "twenty". The dashboard stops with an error.

Fix: Correct Sales!E3 to the number 20 and rerun.

num() is a guard: it is better to stop with a clear message than to publish a dashboard built from text. Because the error happens before output(), the previous Dashboard is not overwritten.

The script runs, but the totals are wrong

A teammate "simplified" one line. No error appears, yet East and West are nonsense.

Fix: Restore num(r[3])*num(r[4]) so revenue is units multiplied by price, validated as numbers.

Adding instead of multiplying produces plausible-looking numbers. Always test against a known expected result before trusting output.

Extension activity: Add a product breakdown

Keep the regional Dashboard exactly as it is and add a Products tab with revenue per product. Blank rows must still be ignored.

Acceptance checks:

  • Baseline still holds: East 160, West 100, Total 260
  • Products tab: Course 120, Book 140
  • A row added after a blank row is included and the blank row is ignored

Original improvement idea from the workshop: Add product breakdown and date filters; test a blank row.

Extension prompt
Update the existing app without removing working features. Add product breakdown and date filters; test a blank row. Return complete updated files, explain changes and give regression tests.
Automation option: Refresh daily after importing transactions; use an explicit spreadsheet ID in scheduled code. Keep this separate from the baseline exercise.

Automation considerations

Rerun-safe: output() replaces the Dashboard and old charts are removed. For a schedule, pass an explicit spreadsheet ID because a time-driven trigger has no active spreadsheet.

Workshop note: Refresh daily after importing transactions; use an explicit spreadsheet ID in scheduled code.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 01: Automated Sales Dashboard. Input tab Sales, exact headers: Date, Region, Product, Units, Unit price. Create buildDashboard() that reads Sales, converts numeric cells, calculates units × price, and replaces a Dashboard tab with regional totals and grand total. Add a column chart and a menu. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: East 160; West 100; total 260. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs.
Match the reference entry point buildDashboard and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/01-automated-sales-dashboard. Base version limitations: No date filter or product breakdown yet.

Knowledge check

  1. Which line protects the dashboard from a price typed as text?

    1. num(r[4]) inside the forEach
    2. s.setFrozenRows(1)
    3. Object.entries(totals)
    Answer

    num(r[4]) inside the forEach Correct: num() throws "Invalid number" for anything that is not a finite number.

  2. You run buildDashboard() three times. How many charts are on the Dashboard?

    1. One
    2. Three
    3. None
    Answer

    One Correct: s.getCharts().forEach(c=>s.removeChart(c)) removes earlier charts before inserting a new one.

  3. Sales!D3 contains "5 units". What happens?

    1. The run stops with Invalid number: 5 units and the old Dashboard stays
    2. West becomes 0
    3. The row is skipped silently
    Answer

    The run stops with Invalid number: 5 units and the old Dashboard stays Correct: num() throws before output() rewrites the Dashboard.

  4. Why is the Total row left out of the chart range?

    1. It would dwarf the regional bars and double-count revenue visually
    2. Charts cannot show text labels
    3. The Total row is not written to the sheet
    Answer

    It would dwarf the regional bars and double-count revenue visually Correct: getRange(1,1,rows.length+1,2) covers the header and regions only.

  5. Your manager wants the dashboard refreshed every morning. What must change first?

    1. Use an explicit spreadsheet ID, because a time-driven trigger has no active spreadsheet
    2. Nothing; install the trigger as is
    3. Switch to Gemini so it can run unattended
    Answer

    Use an explicit spreadsheet ID, because a time-driven trigger has no active spreadsheet Correct: SpreadsheetApp.getActive() returns null in a time-driven trigger, so scheduled code must open the file by ID.

Five-minute presenter demonstration

Open the demo link (temporary workspace; saved learner work is not touched).

Opening hook: Raise your hand if you have ever done this by hand: Manual regional totals are slow and error-prone. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Sales tab and its headers: Date, Region, Product, Units, Unit price. Say what goes in and what should come out.
    Narration: Manual regional totals are slow and error-prone. Practical uses: Small shops, course sales and department reporting.
  2. 0:45–1:30 — Predict and run. Ask the room: Before you run buildDashboard(), what will the Total row show? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: East 160; West 100; total 260.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select buildDashboard() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: buildDashboard() reads every sales row, multiplies units by price and adds the result to a running total for that row's region. It then writes one row per region plus a Total row to a Dashboard tab and draws a column chart.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Sales tab, click cell D2, type 4 in the formula bar and press Enter. Click ▶ Run application again.
    Narration: Workshop challenge: Change East Course units from 3 to 4; total becomes 300.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Rerun-safe: output() replaces the Dashboard and old charts are removed. For a schedule, pass an explicit spreadsheet ID because a time-driven trigger has no active spreadsheet.
    Narration: Baseline limitation: No date filter or product breakdown yet.

Closing takeaway: The totals object accumulates units times price per region; reduce computes the grand total; the chart excludes the total row.

Related resources