DiscoveryVIP · Hands-On AI
PROJECT 10

Intelligent File Organizer

Unorganized files are difficult to retrieve.

Try interactive applicationDownload complete source

What this teaches

Preview rule-based file organization. Household records, finance and HR sample folders.

Start without an account in the local application. Read/edit the input, predict a result, run the current source and verify output. A local document preview is not a real Google Doc; a fixture is not a live model response.

Input and expected result

Input tab: Rules. Entry function: previewMoves().

PrefixDestination
FIN-Finance
HR-People

Expected baseline: Two proposed moves; MISC stays unchanged.

Exact Workspace setup

  1. Download and unzip this project. Use one separate bound script per lesson.
  2. Create a dedicated Drive folder. Create a native Google Sheet inside it, and import starter.csv into a tab named Rules. Check the exact headers above.
  3. Create a native Google Doc named FIN-Budget in the same folder, with this exact text:
    Budget sample
  4. Create a native Google Doc named HR-Onboarding in the same folder, with this exact text:
    Onboarding sample
  5. Create a native Google Doc named MISC-Notes in the same folder, with this exact text:
    Uncategorized sample
  6. Open the Sheet → Extensions → Apps Script. Paste finished Code.gs into the script editor. Save.
  7. Choose previewMoves in the function selector → Run. Review actual requested permissions. Reload the Sheet for the Workshop menu.
  8. Compare output with the baseline above. Check generated documents/drafts manually. No email should be sent.
  9. Perform the original challenge, investigate a failure and test duplicate/partial runs before scheduling. Do not install a trigger just because one manual run succeeded.

Understand the implementation

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

Key operations: startsWith(); getFoldersByName(); insertCheckboxes(); moveTo()

Focused source spotlight

This is an excerpt, not a standalone script. The complete implementation follows.

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();
}

Complete Code.gs

// 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));});}

Four guided activities

Discover and run

Unorganized files are difficult to retrieve.

  1. Inspect the editable Rules table. The starter has 2 records.
  2. Write your predicted result in Prediction. Click Run application.
  3. Compare Output with: Two proposed moves; MISC stays unchanged.
  4. Click Verify baseline; explain one result in Notes.

Expected: Two proposed moves; MISC stays unchanged.

Understand and modify

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

  1. Open Source and read previewMoves. Select the entry function in the walkthrough.
  2. Return to Application. Click Prepare original challenge to create a separate challenge starting state.
  3. For AI projects inspect the revised recorded fixture: this is supplied response data, not newly generated AI.
  4. Run application and use Verify challenge; approval/sidebar projects show extra required steps.

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

Investigate and repair

Rule mismatch

  1. Save a snapshot if you want to keep your experiment.
  2. Click Inject investigation. Change FIN- prefix to XYZ-.
  3. Run application and inspect Output and Execution trace. Some investigations produce wrong/stale content rather than exceptions.
  4. Repair it: Restore FIN-. Preview before approving any move. Run again and explain the root cause.

Expected: startsWith is a case-sensitive prefix test.

Extend and automate

Add an audit log and undo using original folder IDs. Expand the sample allowlist deliberately for real use.

  1. Open Prompts. Select Extend and adapt the requirement to your goal.
  2. Build the feature in Source or export the complete project to Apps Script.
  3. Retest baseline and original challenge before considering scheduling.
  4. Use Resources → Automation readiness. Schedule preview generation only; keep actual moves manual.

Expected: The baseline still works; independent extension checks are designed and reviewed by you.

Original exercise

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

Debugging and troubleshooting

Rule mismatch

Change FIN- prefix to XYZ-.

Hint 1

Check the exact input/response contract and identify the affected field.

Hint 2

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

Hint 3 and repair

Restore FIN-. Preview before approving any move.

startsWith is a case-sensitive prefix test.

Missing tab: check its exact name. Missing document: ensure unique native companion Docs share the Sheet’s dedicated folder. Authorization failure: review source and contact your administrator. Recorded response exhausted: add a new explicit fixture; no live AI is running. Invalid JSON: repair syntax before validating schema. Valid but unsupported content: compare each claim with source records.

Build prompt

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.

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.

Knowledge check and answer key

  1. Which input tab does previewMoves read?
    Answer

    Rules

  2. Which function starts the original application?
    Answer

    previewMoves

  3. What is the baseline output you must verify?
    Answer

    Two proposed moves; MISC stays unchanged.

  4. Does this project need runtime Gemini in the real Workspace baseline?
    Answer

    No; Gemini can help during development only.

  5. What limitation matters before scheduling?
    Answer

    Preview reruns reset approvals; moves alter Drive location. Workshop moves are restricted to the three named sample Docs.

Safe automation

Schedule preview generation only; keep actual moves manual.

Known limitation

Preview reruns reset approvals; moves alter Drive location. Workshop moves are restricted to the three named sample Docs.

Reflect and extend

Explain the transformation using one actual input row. Which incorrect value could still pass structural validation? What happens if the function runs twice or fails after creating one output? Write your explanation before building this extension: Add an audit log and undo using original folder IDs. Expand the sample allowlist deliberately for real use.

Source alignment

Physical slide 30; printed sequence 21 of 48. Reference source SHA-256 2d63fd64031dfa83e9b56ade99c733da12b0b03b79f57ce5dc539d1ffc6fa4d1.

Slide notes use Workshop Info B2. Verified repository resolves the active spreadsheet parent folder; this build follows the repository. Keep companion files in that dedicated lesson folder.

Pinned repository reference · Full source manifest

Five-minute presenter demonstration

0:00–0:45

Action: Open Input. Read Rules headers and first row.

Unorganized files are difficult to retrieve. This application is useful for Household records, finance and HR sample folders. We will run the verified reference code against fictional data.

0:45–1:30

Action: Ask for predictions. Click Run application, then Verify baseline.

Our baseline is Two proposed moves; MISC stays unchanged. The browser displays local results. It has not connected to Google or a model.

1:30–3:00

Action: Open Source. Select previewMoves in the code walkthrough.

Prefix rules create a plan; checkbox approval and parent/rule checks guard the move. The complete code is available to edit and download. The excerpt is not a standalone script.

3:00–4:15

Action: Click Prepare original challenge, inspect the changed inputs, and Run application. Complete extra review/sidebar steps if listed.

Preview, approve FIN-Budget only, then apply moves and verify Finance folder. For AI lessons we edit a recorded response as well as source data. That response must be checked, not trusted.

4:15–5:00

Action: Click Verify challenge. Open Guide and read Automation considerations.

The important limitation is: Preview reruns reset approvals; moves alter Drive location. Workshop moves are restricted to the three named sample Docs. Before scheduling: Schedule preview generation only; keep actual moves manual. Explain the result yourself before moving on.

Launch temporary demo