Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 10 of 30 · Pathway 2 — Google Docs and Drive

Intelligent File Organizer

Unorganized files are difficult to retrieve. Preview rule-based file organization.

Real-world benefit
Household records, finance and HR sample folders.
Technologies
DriveApp, Checkboxes, Preview-first workflow
Required knowledge
Drive folders. The approval checkbox is explained step by step.
Time and level
About 30 minutes · Intermediate
AI requirement
None: deterministic Apps Script
Expected baseline
Two proposed moves; MISC stays unchanged.

Loading the interactive studio…

Introduction

Prefix rules create a plan; checkbox approval and parent/rule checks guard the move. The application's entry point is previewMoves(). Baseline limitation, as stated in the workshop: Preview reruns reset approvals; moves alter Drive location. Workshop moves are restricted to the three named sample Docs.

Key building blocks: startsWith(); getFoldersByName(); insertCheckboxes(); moveTo().

Practical use cases

Household records, finance and HR sample folders.

Prerequisites

  • Drive folders. The approval checkbox is explained step by step.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "Rules" (fictional)
PrefixDestination
FIN-Finance
HR-People

FIN-Budget (Google Doc)

Budget sample

HR-Onboarding (Google Doc)

Onboarding sample

MISC-Notes (Google Doc)

Uncategorized sample

Setup in your own Google account

  1. Download 10-intelligent-file-organizer.zip (Code.gs, starter.csv, sample documents, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Rules, then File → Import → Upload starter.csv → Replace current sheet.
  4. Create native Google Docs in the same folder named exactly: FIN-Budget, HR-Onboarding, MISC-Notes, with the sample text below.
  5. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  6. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  7. Check the result: Two proposed moves; MISC stays unchanged.

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 10-intelligent-file-organizer at commit 4a26d919, SHA-256 2d63fd64031d. Unchanged.

// Intelligent File Organizer
// Entry point: previewMoves; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","previewMoves").addItem("Apply approved moves","applyApprovedMoves").addItem("Check permissions","checkPermissions").addToUi();}
function previewMoves(){
// Preview only; moving files requires a separate approval action.
const rules=input('Rules'),it=folder().getFiles(),rows=[];while(it.hasNext()){const f=it.next();const r=rules.find(r=>f.getName().startsWith(r[0]));if(r && f.getMimeType()===MimeType.GOOGLE_DOCS && ["FIN-Budget","HR-Onboarding","MISC-Notes"].includes(f.getName()))rows.push([f.getId(),f.getName(),r[1],false]);}const s=output('Plan',['ID','Name','Destination','Approve'],rows);if(rows.length)s.getRange(2,4,rows.length).insertCheckboxes();
}
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; }
// Resolve this spreadsheet's actual folder; metadata is informational only.
function folder() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  if (!ss) throw new Error('Open the lesson spreadsheet first.');
  const parents = DriveApp.getFileById(ss.getId()).getParents();
  if (!parents.hasNext()) throw new Error('Move the spreadsheet into a dedicated lesson folder.');
  const actual = parents.next();
  if (parents.hasNext()) throw new Error('Ambiguous parent folder.');
  if (actual.getId() === DriveApp.getRootFolder().getId()) throw new Error('Move the spreadsheet and sample files into a dedicated lesson folder, not My Drive root.');
  return actual;
}
function checkPermissions() {
  const ui = SpreadsheetApp.getUi();
  try {
    const target = folder();
    ui.alert('Folder access passed: ' + target.getName() + '\n' + target.getUrl() + '\nWrite access is checked when the application runs.');
  } catch (e) { ui.alert('Access check failed: ' + e.message); }
}
// Recheck source folder and current rules before moving approved files.
function applyApprovedMoves(){const root=folder(),rules=input('Rules');input('Plan').filter(r=>r[3]===true).forEach(([id,name,dest])=>{const f=DriveApp.getFileById(id);const parents=f.getParents();let inside=false;while(parents.hasNext())if(parents.next().getId()===root.getId())inside=true;if(!inside||f.getMimeType()!==MimeType.GOOGLE_DOCS||!["FIN-Budget","HR-Onboarding","MISC-Notes"].includes(f.getName())||!rules.some(r=>f.getName().startsWith(r[0])&&r[1]===dest))return;const it=root.getFoldersByName(dest);f.moveTo(it.hasNext()?it.next():root.createFolder(dest));});}

How the code works

Beginner explanation

previewMoves() checks each sample document against the prefix rules and writes a Plan with a suggested destination and an unticked Approve box. Nothing moves until you tick boxes and choose Apply approved moves.

Technical explanation

The preview only considers native Google Docs named in an explicit allow-list (the three workshop samples). applyApprovedMoves() re-reads the Plan, keeps rows where Approve === true, and re-verifies that each file is still inside the lesson folder, is still a Doc and still matches a current rule for that destination before calling moveTo(). Destination folders are created inside the lesson folder if missing.

Slide excerpt

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

function previewMoves(){
// Preview only; moving files requires a separate approval action.
const rules=input('Rules'),it=folder().getFiles(),rows=[];while(it.hasNext()){const f=it.next();const r=rules.find(r=>f.getName().startsWith(r[0]));if(r && f.getMimeType()===MimeType.GOOGLE_DOCS && ["FIN-Budget","HR-Onboarding","MISC-Notes"].includes(f.getName()))rows.push([f.getId(),f.getName(),r[1],false]);}const s=output('Plan',['ID','Name','Destination','Approve'],rows);if(rows.length)s.getRange(2,4,rows.length).insertCheckboxes();
}

Common mistakes

  • Moving files in the same function that decides where they go.
  • Trusting an edited Plan without rechecking the rules.
  • Removing the allow-list before you have tested on copies.

Run it and expected output

Choose Workshop → Run application (runs previewMoves()). Expected: Two proposed moves; MISC stays unchanged.

Original workshop exercise

Preview, approve FIN-Budget only, then apply moves and verify Finance folder.

Troubleshooting and debugging

A typo in a rule

The finance prefix was typed as FIN_ instead of FIN-.

Fix: Correct the prefix to FIN-.

Rules are data. Small typos silently change behavior, which is why the preview step exists.

A tampered plan is refused

Someone changed FIN-Budget's destination in the Plan to "Archive" and approved it. Apply did nothing.

Fix: Regenerate the preview and approve the rule-based destination.

Rechecking at apply time protects against edited or stale plans.

Extension activity: Audit log and undo

Record every applied move in a Move Log with the original folder ID, and add undoMoves() that moves logged files back.

Acceptance checks:

  • Approved move is logged
  • undoMoves() returns the file to the lesson folder

Original improvement idea from the workshop: Add an audit log and undo using original folder IDs. Expand the sample allowlist deliberately for real use.

Extension prompt
Update the existing app without removing working features. Add an audit log and undo using original folder IDs. Return complete updated files, explain changes and give regression tests.
Automation option: Schedule preview generation only; keep actual moves manual. Keep this separate from the baseline exercise. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access.

Automation considerations

Schedule the preview only; keep actual moves manual. Preview reruns reset approvals.

Workshop note: Schedule preview generation only; keep actual moves manual.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 10: Intelligent File Organizer. Input tab Rules, exact headers: Prefix, Destination. Create previewMoves() for direct files matching prefixes; write file ID, name, destination and approval checkbox to Plan. Create applyApprovedMoves() that moves only approved matching files within lesson folder; never delete. 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: Two proposed moves; MISC stays unchanged. 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 previewMoves and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/10-intelligent-file-organizer. Base version limitations: Preview reruns reset approvals; moves alter Drive location. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access. Never require a manually configured folder ID. Keep required native sample Docs beside the spreadsheet; reject My Drive root. Restrict moves and previews to the named sample Docs FIN-Budget, HR-Onboarding, MISC-Notes; retain approval and parent checks.

Knowledge check

  1. Why are preview and apply separate functions?

    1. A person reviews the proposed moves before anything changes
    2. Apps Script cannot move files and list them in one function
    3. To use two triggers
    Answer

    A person reviews the proposed moves before anything changes Correct: preview-first is the safe pattern for file operations.

  2. Why does MISC-Notes never appear in the Plan?

    1. No rule prefix matches it
    2. It is not a Google Doc
    3. It is too old
    Answer

    No rule prefix matches it Correct: only FIN- and HR- rules exist.

  3. What does r[3]===true check?

    1. That the Approve checkbox is ticked
    2. That the file exists
    3. That the rule is valid
    Answer

    That the Approve checkbox is ticked Correct: checkbox values are booleans.

  4. Apply approved moves did nothing although a row is ticked. A likely reason?

    1. The destination no longer matches a current rule
    2. Drive is offline
    3. Checkboxes are always false
    Answer

    The destination no longer matches a current rule Correct: the safety recheck skips rows that do not match.

  5. Could this run nightly and move files automatically?

    1. Schedule only the preview; keep moves manual with approval
    2. Yes, remove the checkbox
    3. Yes, and delete unmatched files
    Answer

    Schedule only the preview; keep moves manual with approval Correct: automation proposes, a person approves.

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: Unorganized files are difficult to retrieve. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Rules tab and its headers: Prefix, Destination. Say what goes in and what should come out.
    Narration: Unorganized files are difficult to retrieve. Practical uses: Household records, finance and HR sample folders.
  2. 0:45–1:30 — Predict and run. Ask the room: previewMoves() runs. How many files are moved? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: Two proposed moves; MISC stays unchanged.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select previewMoves() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: previewMoves() checks each sample document against the prefix rules and writes a Plan with a suggested destination and an unticked Approve box. Nothing moves until you tick boxes and choose Apply approved moves.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Click Workshop → Run application (runs previewMoves()). Select the Plan tab, click cell D2, type TRUE in the formula bar and press Enter. Click Workshop → Apply approved moves (runs applyApprovedMoves()).
    Narration: Workshop challenge: Preview, approve FIN-Budget only, then apply moves and verify Finance folder.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Schedule the preview only; keep actual moves manual. Preview reruns reset approvals.
    Narration: Baseline limitation: Preview reruns reset approvals; moves alter Drive location. Workshop moves are restricted to the three named sample Docs.

Closing takeaway: Prefix rules create a plan; checkbox approval and parent/rule checks guard the move.

Related resources