From df72b9ec27e91ed368df0c5022bb4f6ff97137d3 Mon Sep 17 00:00:00 2001 From: 404oops Date: Tue, 13 Oct 2026 15:48:06 +0200 Subject: [PATCH] Add Puter file selection and export to category recipe --- .../clean-up-imported-categories.html | 361 ++++++++- .../recipes/clean-up-imported-categories.md | 211 ++++- .../clean-up-imported-categories.test.mjs | 725 ++++++++++++++++-- 3 files changed, 1212 insertions(+), 85 deletions(-) diff --git a/src/docs/src/playground/examples/clean-up-imported-categories.html b/src/docs/src/playground/examples/clean-up-imported-categories.html index 3c1ea41c0..6f765ebd4 100644 --- a/src/docs/src/playground/examples/clean-up-imported-categories.html +++ b/src/docs/src/playground/examples/clean-up-imported-categories.html @@ -1,10 +1,84 @@ -
Asking for suggestions...
+

+ + + +

+

Open a CSV file with a header row and a category column. Nothing is sent until you open one.

+ + + + +
LabelRowsCategory
+ diff --git a/src/docs/src/recipes/clean-up-imported-categories.md b/src/docs/src/recipes/clean-up-imported-categories.md index 06dabd593..c45e8a13e 100644 --- a/src/docs/src/recipes/clean-up-imported-categories.md +++ b/src/docs/src/recipes/clean-up-imported-categories.md @@ -7,40 +7,153 @@ order: 70 Rows imported from a bank or budgeting export rarely agree on categories. One file can hold `groceries`, `Groceries ` with a trailing space, `coffee shops`, -and `???`. In this recipe, [`puter.ai.chat()`](/AI/chat/) suggests a category -for each distinct label, the user reviews the suggestions in your app, and plain -code applies the approved categories and writes a new CSV file. +and `???`. In this recipe, the user opens a CSV file from their Puter account, +[`puter.ai.chat()`](/AI/chat/) suggests a category for each distinct label, the +user reviews the suggestions in your app, and plain code applies the approved +categories and saves a new CSV file to the user's Puter account. The AI only sees the distinct labels, never dates, descriptions, or amounts. Its reply is only a suggestion, so no row changes until the user approves the -review. +review. The file the user opened stays unchanged. -## Start From Parsed Rows +## Open a CSV File -Parse the file with a CSV parser such as Papa Parse, with the header row on and -type conversion off so amounts like `-4.50` stay as written. The recipe works on -an array of objects with one string per column: +The user picks the file with +[`puter.ui.showOpenFilePicker()`](/UI/showOpenFilePicker/), which opens the +Puter file picker on the user's Desktop folder and resolves to an +[`FSItem`](/Objects/fsitem/) for the chosen file. The +[`read()`](/Objects/fsitem/#read) method of that item resolves to a `Blob` with +the file's contents. When the user closes the picker in the Puter desktop, the +promise from [`puter.ui.showOpenFilePicker()`](/UI/showOpenFilePicker/) stays +pending, and its `undefinedOnCancel` promise resolves to `undefined` instead. +When your app runs as a website, the picker opens in a popup window. Closing +that popup resolves the picker's own promise to an object whose `msg` is +`'fileOpenCanceled'`. The `openCsvFile()` function waits for whichever settles +first and treats both forms as a cancel, so it resolves to `null` when the user +cancels and rejects when the picker fails. + +The `accept: '.csv'` option only filters what the picker shows, so the function +checks the file name and the size of the `Blob` it reads. The cap of 1 MiB and +10,000 rows is a limit chosen for this recipe. All the picker options are listed +on [`puter.ui.showOpenFilePicker()`](/UI/showOpenFilePicker/). + +Your app loads [Papa Parse](https://www.papaparse.com/) to parse the text, for +example from `https://cdn.jsdelivr.net/npm/papaparse@5.5.3/papaparse.min.js`, +which defines the `Papa` global. The `parseCsv()` function turns the header row +on and type conversion off, so amounts like `-4.50` and labels like `Groceries ` +stay exactly as written. It rejects a file with parse errors, an empty or +repeated column name, no `category` column, or a row without one text value per +column: + +```js;clean-up-imported-categories +const MAX_FILE_BYTES = 1024 * 1024; +const MAX_ROWS = 10_000; +const FILE_TOO_LARGE = 'Pick a CSV file of at most 1 MiB.'; + +function parseCsv (text) { + const { data, errors, meta } = Papa.parse(text, { + header: true, + dynamicTyping: false, + skipEmptyLines: true, + delimiter: ',', + // One row over the cap is enough to reject the file without parsing the rest. + preview: MAX_ROWS + 1, + }); + if ( errors.length > 0 ) { + throw new Error(`The file isn't valid CSV (${ errors[0].message }).`); + } + const columns = meta.fields ?? []; + if ( Object.keys(meta.renamedHeaders ?? {}).length > 0 || new Set(columns).size !== columns.length ) { + throw new Error('Every column in the header row needs a different name.'); + } + if ( columns.some(column => column.trim() === '') ) { + throw new Error('Every column in the header row needs a name.'); + } + if ( ! columns.includes('category') ) { + throw new Error('The file needs a category column.'); + } + if ( data.length > MAX_ROWS ) { + throw new Error(`The file has more than ${ MAX_ROWS } rows.`); + } + const bad = data.findIndex(row => Object.keys(row).length !== columns.length + || ! columns.every(column => typeof row[column] === 'string')); + if ( bad !== -1 ) { + throw new Error(`Row ${ bad + 1 } doesn't have one value per column.`); + } + return { columns, rows: data }; +} + +async function openCsvFile () { + const request = puter.ui.showOpenFilePicker({ multiple: false, accept: '.csv' }); + // A failure only rejects the picker's own promise. A desktop cancel settles undefinedOnCancel, + // and a website popup cancel resolves the picker's own promise with a cancel message. + const file = await Promise.race([request, request.undefinedOnCancel]); + if ( file === undefined || file?.msg === 'fileOpenCanceled' ) { + return null; + } + if ( Array.isArray(file) || file?.isDir || typeof file?.read !== 'function' || ! /\.csv$/i.test(String(file.name)) ) { + throw new Error('Pick one .csv file.'); + } + if ( typeof file.size === 'number' && file.size > MAX_FILE_BYTES ) { + throw new Error(FILE_TOO_LARGE); + } + const blob = await file.read(); + if ( ! (blob instanceof Blob) ) { + throw new Error('The file could not be read.'); + } + // The reported size can be stale, so the bytes actually read are checked too. + if ( blob.size > MAX_FILE_BYTES ) { + throw new Error(FILE_TOO_LARGE); + } + return { name: file.name, ...parseCsv(await blob.text()) }; +} +``` + +Call `openCsvFile()` from your Open button's click handler, before any other +`await`, so the browser allows the picker popup. If it throws, show the error +and keep any review the user already has. The rest of this recipe works on the +opened file, so this code stops before asking the AI when the user cancels. In +a click handler, return instead of throwing: ```js -const rows = [ - { date: '2026-09-01', description: 'Corner Grocery', amount: '-42.10', category: 'groceries' }, - { date: '2026-09-02', description: 'City Transit', amount: '-2.75', category: 'Transport' }, - { date: '2026-09-03', description: 'Cafe "Bean", Main St', amount: '-4.50', category: 'coffee shops' }, - { date: '2026-09-04', description: 'Payroll', amount: '1,250.00', category: 'Salary' }, - { date: '2026-09-05', description: 'Hardware store', amount: '-18.90', category: 'Groceries ' }, - { date: '2026-09-06', description: '=HYPERLINK("https://example.com","Refund")', amount: '-0.01', category: '???' }, -]; +const imported = await openCsvFile(); +if ( imported === null ) { + throw new Error('No file was opened.'); +} +const rows = imported.rows; ``` +For a file with this text, `rows` holds one object per line: + +```text +date,description,amount,category +2026-09-01,Corner Grocery,-42.10,groceries +2026-09-02,City Transit,-2.75,Transport +2026-09-03,"Cafe ""Bean"", Main St",-4.50,coffee shops +2026-09-04,Payroll,"1,250.00",Salary +2026-09-05,Hardware store,-18.90,"Groceries " +2026-09-06,"=HYPERLINK(""https://example.com"",""Refund"")",-0.01,??? +``` + +Every value is the text from the file, so the third row is: + +```json +{ "date": "2026-09-03", "description": "Cafe \"Bean\", Main St", "amount": "-4.50", "category": "coffee shops" } +``` + +To try the whole flow with a CSV file from your Puter account, run the first +code block in this section in the playground. It asks for suggestions after you +open a file, shows the review, and saves the CSV file you approve. + Only the `category` column is sent. If people can type free text into it, check what it holds before sending it anywhere. ## Ask for Suggestions Send the distinct labels with the categories your app uses. This first try -takes the labels straight from the sample rows: +takes the labels straight from the rows of the file: -```js;clean-up-imported-categories +```js const CATEGORIES = ['Groceries', 'Dining', 'Transport', 'Income', 'Shopping', 'Other']; async function suggestCategories (labels) { @@ -95,10 +208,6 @@ the reply text a string for every model. All the options are listed on [`puter.ai.chat()`](/AI/chat/). Not every model enforces the schema strictly, and a label can contain instructions, so the next step checks the reply. -To try this request, run the code block above in the playground. It sends the -sample labels and shows the raw reply as text. The rest of this recipe checks -that reply and turns it into a review the user approves. - ## Check the Proposal Keep only a known category for a known label. Anything else leaves the label @@ -221,16 +330,16 @@ async function prepareReview (rows, reply) { } ``` -In your app, pass only the parsed rows. `await prepareReview(rows)` checks them -and then makes one request, or throws without a request if they are invalid. -For the sample rows, reuse the reply from the first try instead of asking again: +In your app, pass only the rows of the file. `await prepareReview(rows)` checks +them and then makes one request, or throws without a request if they are +invalid. Here, reuse the reply from the first try instead of asking again: ```js const review = await prepareReview(rows, reply); ``` The review is plain data. If the AI leaves out `Groceries ` and suggests an -unknown category for `???`, the review for the sample rows looks like this: +unknown category for `???`, the review for the sample file looks like this: ```json { @@ -352,8 +461,52 @@ For these entries, `result.unresolved` is `1` and `result.csv` holds this text: "2026-09-06","'=HYPERLINK(""https://example.com"",""Refund"")","-0.01","???","" ``` -Save the string or offer it as a download with whatever your platform provides. -To skip the AI step next time for labels the user already approved, save the -approved entries with [`puter.kv`](/KV/), as in +## Save the CSV to Puter + +To save the result, pass `result.csv` to +[`puter.ui.showSaveFilePicker()`](/UI/showSaveFilePicker/). It opens the Puter +save dialog, where the user picks a folder and a file name, and writes the text +to the file the user chose. When the user closes the dialog in the Puter +desktop, its promise stays pending, and its `undefinedOnCancel` promise resolves +to `undefined` instead. In a website, closing the save popup resolves the +dialog's own promise to an object whose `msg` is `'fileSaveCanceled'`. The +`saveCsvFile()` function treats both forms as a cancel and resolves to `null`. +It resolves to the [`FSItem`](/Objects/fsitem/) of the saved file only when the +result has a file name. It rejects when the save fails or the result doesn't +name a saved file: + +```js +async function saveCsvFile (csv, suggestedName) { + const request = puter.ui.showSaveFilePicker(csv, suggestedName); + // A desktop cancel settles undefinedOnCancel, and a website popup cancel resolves with a cancel message. + const saved = await Promise.race([request, request.undefinedOnCancel]); + if ( saved === undefined || saved?.msg === 'fileSaveCanceled' ) { + return null; + } + // Only a result that names the saved file confirms the save. + if ( typeof saved?.name !== 'string' || saved.name === '' ) { + throw new Error('The save dialog did not return the saved file, so the save could not be confirmed.'); + } + return saved; +} +``` + +Call `saveCsvFile()` from your Save button's click handler, before any other +`await`, so the browser allows the dialog popup. Pass the `result` the user +approved. Tell the user the file is saved only when the call resolves to an +item. When it resolves to `null`, the user canceled and no file was saved. A +rejection can come after the file was written, so tell the user the save could +not be confirmed and to check the destination before retrying. Keep `result` in +both cases, so the user can save again: + +```js +const savedFile = await saveCsvFile(result.csv, imported.name.replace(/\.csv$/i, '-cleaned.csv')); +``` + +If the user changes a category after approving, or opens another file, the +earlier approval no longer counts. Discard `result`, ask the user to approve the +review again, and call `applyReview()` from that approval before the next save, +so the saved file matches what the user approved. To skip the AI step next time for labels the user already +approved, save the approved entries with [`puter.kv`](/KV/), as in [Save User Settings](/recipes/save-user-settings/), and only ask about new labels. diff --git a/src/docs/src/recipes/clean-up-imported-categories.test.mjs b/src/docs/src/recipes/clean-up-imported-categories.test.mjs index 327068b52..ae8daf641 100644 --- a/src/docs/src/recipes/clean-up-imported-categories.test.mjs +++ b/src/docs/src/recipes/clean-up-imported-categories.test.mjs @@ -3,7 +3,8 @@ import vm from 'node:vm'; import { describe, expect, it, vi } from 'vitest'; // Executes the recipe's own JS blocks, in order, so the tests cover exactly the -// code readers copy. The context has no DOM and only a mocked `puter.ai.chat`. +// code readers copy. The context has no DOM. `puter.ai.chat`, the `puter.ui` +// pickers, and the `Papa` global are mocks at the browser and network boundary. const markdown = readFileSync(new URL('./clean-up-imported-categories.md', import.meta.url), 'utf8'); const blocks = [...markdown.matchAll(/^```js(?:;[\w-]+)?\n([\s\S]*?)^```$/gm)].map(([, code]) => code); const source = blocks.join('\n'); @@ -25,18 +26,132 @@ const sampleReply = () => reply([ { label: '???', category: 'Fraud' }, ]); +// -- File, picker, and parser boundaries -- + +const MAX_FILE_BYTES = 1024 * 1024; + +// Synthetic file contents, not user data. +const SAMPLE_FILE = [ + 'date,description,amount,category', + '2026-09-01,Corner Grocery,-42.10,groceries', + '2026-09-02,City Transit,-2.75,Transport', + '2026-09-03,"Cafe ""Bean"", Main St",-4.50,coffee shops', + '2026-09-04,Payroll,"1,250.00",Salary', + '2026-09-05,Hardware store,-18.90,"Groceries "', + '2026-09-06,"=HYPERLINK(""https://example.com"",""Refund"")",-0.01,???', + '', +].join('\r\n'); +const SAMPLE_COLUMNS = ['date', 'description', 'amount', 'category']; +const SAMPLE_ROWS = [ + { date: '2026-09-01', description: 'Corner Grocery', amount: '-42.10', category: 'groceries' }, + { date: '2026-09-02', description: 'City Transit', amount: '-2.75', category: 'Transport' }, + { date: '2026-09-03', description: 'Cafe "Bean", Main St', amount: '-4.50', category: 'coffee shops' }, + { date: '2026-09-04', description: 'Payroll', amount: '1,250.00', category: 'Salary' }, + { date: '2026-09-05', description: 'Hardware store', amount: '-18.90', category: 'Groceries ' }, + { date: '2026-09-06', description: '=HYPERLINK("https://example.com","Refund")', amount: '-0.01', category: '???' }, +]; + +/** The result shape of `Papa.parse()` with `header: true`. */ +function papaResult (fields, data, { errors = [], renamedHeaders } = {}) { + return { + data, + errors, + meta: { + delimiter: ',', + linebreak: '\r\n', + aborted: false, + truncated: false, + cursor: 0, + fields, + ...(renamedHeaders ? { renamedHeaders } : {}), + }, + }; +} + /** - * Runs the blocks as one async body, which for the full source also prepares - * and applies the recipe's sample review, and returns its top-level declarations. + * Stands in for the Papa Parse global, which can't be installed here. Each known + * file text maps to the result Papa Parse returns for it, and any other text fails. */ -async function loadRecipe (chat = vi.fn(async () => sampleReply()), code = source) { +function fakePapa (extra = []) { + const results = new Map([[SAMPLE_FILE, papaResult(SAMPLE_COLUMNS, SAMPLE_ROWS)], ...extra]); + return { + parse: vi.fn(text => { + if ( ! results.has(text) ) { + throw new Error(`No parse result for ${ JSON.stringify(String(text).slice(0, 40)) }`); + } + return structuredClone(results.get(text)); + }), + }; +} + +/** Picker promises as `puter.ui` returns them, with `undefinedOnCancel` attached. */ +function pickerResolving (value) { + const request = Promise.resolve(value); + request.undefinedOnCancel = Promise.resolve(value); + return request; +} + +function pickerCancelled () { + const request = new Promise(() => {}); + request.undefinedOnCancel = Promise.resolve(undefined); + return request; +} + +function pickerRejecting (error) { + const request = Promise.reject(error); + request.undefinedOnCancel = new Promise(() => {}); + return request; +} + +/** A website popup cancel, which resolves the picker's own promise with the popup's message. */ +function pickerPopupCancelled (msg) { + const request = Promise.resolve({ msg, original_msg_id: 1 }); + request.undefinedOnCancel = new Promise(() => {}); + return request; +} + +/** A picked file shaped like an `FSItem`, whose `read()` resolves to a Blob. */ +function fakeFile (name, content, { type = 'text/csv', size = new Blob([content]).size, ...rest } = {}) { + return { + name, + path: `/test-user/Desktop/${ name }`, + size, + isDir: false, + read: vi.fn(async () => new Blob([content], { type })), + ...rest, + }; +} + +const savedItem = name => ({ name, path: `/test-user/Desktop/${ name }`, isDir: false }); + +function fakeUi ({ file = fakeFile('september.csv', SAMPLE_FILE) } = {}) { + return { + showOpenFilePicker: vi.fn(() => pickerResolving(file)), + showSaveFilePicker: vi.fn((content, name) => pickerResolving(savedItem(name))), + }; +} + +/** + * Runs the blocks as one async body, which for the full source also opens the + * sample file, prepares and applies the recipe's sample review, and saves the + * result, and returns its top-level declarations. + */ +async function loadRecipe (chat = vi.fn(async () => sampleReply()), code = source, { ui = fakeUi(), Papa = fakePapa() } = {}) { const names = [...code.matchAll(/^(?:async )?(?:function|const) (\w+)/gm)].map(([, name]) => name); - const context = vm.createContext({ puter: { ai: { chat } } }); + const context = vm.createContext({ puter: { ai: { chat }, ui }, Papa, Blob }); const recipe = await vm.runInContext( `(async () => {\n${ code }\nreturn { ${ names.join(', ') } };\n})()`, context, ); - return { recipe, chat }; + return { recipe, chat, ui, Papa, context }; +} + +/** Loads the recipe, then points it at fresh boundaries for one call. */ +async function withBoundaries ({ file, ui = fakeUi({ file }), Papa = fakePapa(), chat = vi.fn(async () => sampleReply()) } = {}) { + const { recipe, context } = await loadRecipe(); + context.puter = { ai: { chat }, ui }; + context.Papa = Papa; + return { recipe, ui, Papa, chat }; } const expectLabelsOnly = (recipe, chat) => { @@ -56,56 +171,570 @@ const expectLabelsOnly = (recipe, chat) => { }; describe('first try', () => { - it('runs on its own and returns the reply text for the sample labels', async () => { - const { recipe, chat } = await loadRecipe(undefined, firstTry); + it('runs on its own from the opened file and returns the reply text for its labels', async () => { + const { recipe, chat, ui } = await loadRecipe(undefined, firstTry); + expect(ui.showOpenFilePicker).toHaveBeenCalledTimes(1); expect(chat).toHaveBeenCalledTimes(1); expectLabelsOnly(recipe, chat); expect(recipe.reply).toBe(sampleReply().message.content); expect(recipe.prepareReview).toBeUndefined(); - }); -}); - -// The playground companion for the first try, run with a stub element that only accepts text. -const companionHtml = readFileSync(new URL('../playground/examples/clean-up-imported-categories.html', import.meta.url), 'utf8'); -const companionScript = companionHtml.match(/