Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 05 of 30 · Pathway 1 — Spreadsheet Automation

Automated Inventory Monitor

Low stock can go unnoticed until supplies run out. Detect low stock automatically.

Real-world benefit
Office supplies, classroom materials and small inventory.
Technologies
Google Sheets, filter(), Time-driven triggers, PropertiesService
Required knowledge
Comparing numbers (less than, equal to).
Time and level
About 20 minutes · Beginner
AI requirement
None: deterministic Apps Script
Expected baseline
A01 and A03 appear in Alerts.

Loading the interactive studio…

Introduction

filter selects quantities at or below reorder level; output replaces the alert report. The application's entry point is checkInventory(). Baseline limitation, as stated in the workshop: Alerts tab only; no email notification.

Key building blocks: filter(); numeric comparisons; ScriptApp.newTrigger(); getProjectTriggers().

Practical use cases

Office supplies, classroom materials and small inventory.

Prerequisites

  • Comparing numbers (less than, equal to).
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "Inventory" (fictional)
SKUItemStockReorder level
A01Paper410
A02Pens2010
A03Folders55

Setup in your own Google account

  1. Download 05-automated-inventory-monitor.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 Inventory, 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: A01 and A03 appear in Alerts.

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 05-automated-inventory-monitor at commit 4a26d919, SHA-256 dca4b3ac18e3. Unchanged.

// Automated Inventory Monitor
// Entry point: checkInventory; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","checkInventory").addItem("Install daily trigger","installDaily").addToUi();}
function checkInventory(){
// Filter only products at or below their reorder threshold.
output('Alerts',['SKU','Item','Stock','Reorder level'],input('Inventory').filter(r=>num(r[2])<=num(r[3])));
}
function input(name) { const s=workshopSpreadsheet().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=workshopSpreadsheet(); 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);}
function installDaily(){PropertiesService.getScriptProperties().setProperty("WORKSHOP_TRIGGER_SHEET",SpreadsheetApp.getActiveSpreadsheet().getId());if(!ScriptApp.getProjectTriggers().some(t=>t.getHandlerFunction()==='checkInventory'))ScriptApp.newTrigger('checkInventory').timeBased().everyDays(1).create();}

function workshopSpreadsheet(){const active=SpreadsheetApp.getActiveSpreadsheet(); if(active)return active; const id=PropertiesService.getScriptProperties().getProperty("WORKSHOP_TRIGGER_SHEET"); if(!id)throw new Error("Run Install daily trigger from your copied spreadsheet first."); return SpreadsheetApp.openById(id);}

How the code works

Beginner explanation

checkInventory() keeps only the products whose stock is at or below the reorder level and writes them to an Alerts tab. The menu can also install a daily trigger so the check runs every morning.

Technical explanation

input() and output() go through workshopSpreadsheet(), which returns the active spreadsheet when a person runs the code, and otherwise opens the spreadsheet whose ID installDaily() saved in Script Properties. That is required because a time-driven trigger has no active spreadsheet. installDaily() checks getProjectTriggers() first so it never creates duplicate triggers.

Slide excerpt

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

function checkInventory(){
// Filter only products at or below their reorder threshold.
output('Alerts',['SKU','Item','Stock','Reorder level'],input('Inventory').filter(r=>num(r[2])<=num(r[3])));
}

Common mistakes

  • Installing the trigger twice and getting two runs a day.
  • Using SpreadsheetApp.getActive() in code that will run from a trigger.
  • Sending an email on every run instead of only when status changes.

Run it and expected output

Choose Workshop → Run application (runs checkInventory()). Expected: A01 and A03 appear in Alerts.

Original workshop exercise

Change A02 stock to 10; expect three alerts.

Troubleshooting and debugging

A missing reorder level

A new product was added without a reorder level.

Fix: Fill in the reorder level (10).

Treating blank as zero would silently hide a low-stock product. Failing loudly is safer.

The boundary case disappears

After a code edit, Folders (5 in stock, level 5) is no longer reported.

Fix: Use <= so stock at the reorder level triggers an alert.

Off-by-one comparisons are the most common rule bug. Always include a boundary row in your test data.

Extension activity: Alert history that only records changes

Keep the Alerts tab as is and add an Alert History tab that records a SKU only when it newly enters the low-stock list, so reruns do not repeat entries.

Acceptance checks:

  • Alerts still lists A01 and A03
  • Running twice records each SKU once
  • A new low-stock SKU adds exactly one history row

Original improvement idea from the workshop: Add an alert history and notify only when status changes, using drafts.

Extension prompt
Update the existing app without removing working features. Add an alert history and notify only when status changes, using drafts. Return complete updated files, explain changes and give regression tests.
Automation option: The existing Install daily trigger menu creates a daily check; verify background spreadsheet access. Keep this separate from the baseline exercise.

Automation considerations

Designed for a daily trigger: Alerts is replaced each run, the trigger is installed once, and the spreadsheet ID is stored for background runs. It reports; it does not reorder anything.

Workshop note: Install daily trigger from your own copied spreadsheet; the installer stores its ID for background execution.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 05: Automated Inventory Monitor. Input tab Inventory, exact headers: SKU, Item, Stock, Reorder level. Create checkInventory() that writes items with stock <= reorder level to Alerts; add menu and optional daily trigger installer that avoids duplicate triggers. No email sending. 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: A01 and A03 appear in Alerts. 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 checkInventory and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/05-automated-inventory-monitor. Base version limitations: Alerts tab only; no email notification. For scheduled execution, save the current spreadsheet ID when installing the trigger and use openById when no active spreadsheet exists. Reinstall in each copy.

Knowledge check

  1. Why does the code store the spreadsheet ID in Script Properties when installing the trigger?

    1. A time-driven trigger has no active spreadsheet, so the code must open it by ID
    2. To make the sheet load faster
    3. Triggers need the ID to send email
    Answer

    A time-driven trigger has no active spreadsheet, so the code must open it by ID Correct: workshopSpreadsheet() falls back to openById() with the saved ID.

  2. installDaily() is clicked twice. How many triggers exist?

    1. One
    2. Two
    3. Zero
    Answer

    One Correct: getProjectTriggers().some(…) prevents a second trigger for checkInventory.

  3. Is checkInventory() reporting or taking action?

    1. Reporting: it lists low stock but orders nothing
    2. Taking action: it places orders
    3. Both
    Answer

    Reporting: it lists low stock but orders nothing Correct: monitoring and acting are separate decisions; acting needs human review.

  4. The trigger run fails with "Run Install daily trigger from your copied spreadsheet first." Why?

    1. WORKSHOP_TRIGGER_SHEET is missing from Script Properties
    2. The Inventory tab is empty
    3. The reorder level is blank
    Answer

    WORKSHOP_TRIGGER_SHEET is missing from Script Properties Correct: without an active spreadsheet the code needs the stored ID.

  5. You want an email when stock is low. Safest next step?

    1. Create a draft or notification only when a SKU newly becomes low, and test reruns first
    2. Email every product on every run
    3. Email automatically from a custom function
    Answer

    Create a draft or notification only when a SKU newly becomes low, and test reruns first Correct: notify on change, avoid duplicates, and keep a person in the loop.

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: Low stock can go unnoticed until supplies run out. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Inventory tab and its headers: SKU, Item, Stock, Reorder level. Say what goes in and what should come out.
    Narration: Low stock can go unnoticed until supplies run out. Practical uses: Office supplies, classroom materials and small inventory.
  2. 0:45–1:30 — Predict and run. Ask the room: Which SKUs will appear in Alerts? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: A01 and A03 appear in Alerts.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select checkInventory() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: checkInventory() keeps only the products whose stock is at or below the reorder level and writes them to an Alerts tab. The menu can also install a daily trigger so the check runs every morning.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Inventory tab, click cell C3, type 10 in the formula bar and press Enter. Click ▶ Run application again.
    Narration: Workshop challenge: Change A02 stock to 10; expect three alerts.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Designed for a daily trigger: Alerts is replaced each run, the trigger is installed once, and the spreadsheet ID is stored for background runs. It reports; it does not reorder anything.
    Narration: Baseline limitation: Alerts tab only; no email notification.

Closing takeaway: filter selects quantities at or below reorder level; output replaces the alert report.

Related resources