import { useState, useRef } from 'react' import { useNavigate } from 'react-router-dom' import { api } from '../api' import SampleTable from '../components/SampleTable.jsx' const FIELD_TYPES = ['text', 'numeric', 'date'] // Ticked into the view by default when a bank feed sample contains them const FEED_DEFAULT_VIEW = ['date', 'description', 'payee', 'amount'] export default function SourceList({ sources, setSources, setSource }) { const navigate = useNavigate() const [creating, setCreating] = useState(false) const [form, setForm] = useState({ name: '', constraint_fields: '', fields: [], schema: [], importSample: true }) const [createError, setCreateError] = useState('') const [createLoading, setCreateLoading] = useState(false) const [csvFileName, setCsvFileName] = useState('') const [bridgeAccounts, setBridgeAccounts] = useState(null) const [bridgeLoading, setBridgeLoading] = useState(false) const [bridgeError, setBridgeError] = useState('') const [sampleInfo, setSampleInfo] = useState(null) const fileRef = useRef() async function loadBridgeAccounts() { setBridgeLoading(true) setBridgeError('') try { const res = await api.getSimpleFinAccounts() setBridgeAccounts(res.accounts || []) if (res.errors?.length) setBridgeError(res.errors.join('; ')) } catch (err) { setBridgeError(err.message) } finally { setBridgeLoading(false) } } // Writes only config — constraint_fields and global_picklist are left NULL so // update_source keeps whatever is already stored. async function handleSelectFeedAccount(accountId) { if (!accountId) { // Clearing the feed only resets fields we populated, not a loaded CSV setForm(f => csvFileName ? { ...f, simplefin_account_id: '' } : { ...f, simplefin_account_id: '', fields: [], schema: [], constraint_fields: '', sampleRows: [], }) setSampleInfo(null) return } setForm(f => ({ ...f, simplefin_account_id: accountId })) setBridgeLoading(true) setBridgeError('') try { const res = await api.getSimpleFinSample(accountId) const names = res.fields.map(f => f.name) setSampleInfo({ fetched: res.fetched, fields: res.fields.length }) if (res.errors?.length) setBridgeError(res.errors.join('; ')) setForm(f => ({ ...f, fields: res.fields, sampleRows: res.sampleRows || [], schema: FEED_DEFAULT_VIEW.filter(n => names.includes(n)).map((name, i) => ({ name, type: res.fields.find(sf => sf.name === name).type, seq: i + 1, })), // Only default the constraint if the sample actually has an id constraint_fields: f.constraint_fields || (names.includes('id') ? 'id' : ''), })) } catch (err) { setBridgeError(err.message) } finally { setBridgeLoading(false) } } async function handleSuggest(e) { const file = e.target.files[0] if (!file) return setCsvFileName(file.name) try { const suggestion = await api.suggestSource(file) setForm(f => ({ ...f, fields: suggestion.fields, constraint_fields: '', schema: suggestion.fields.map(f => ({ name: f.name, type: f.type, seq: suggestion.fields.indexOf(f) + 1 })), sampleRows: suggestion.sampleRows || [] })) } catch (err) { setCreateError(err.message) } } async function handleCreate(e) { e.preventDefault() setCreateError('') const constraintArr = form.constraint_fields.split(',').map(s => s.trim()).filter(Boolean) if (!form.name || constraintArr.length === 0) { setCreateError('Name and at least one constraint field required') return } setCreateLoading(true) try { const config = form.schema.length > 0 ? { fields: form.schema } : {} if (form.simplefin_account_id) { config.simplefin = { account_id: form.simplefin_account_id } } await api.createSource({ name: form.name, constraint_fields: constraintArr, config, global_picklist: form.global_picklist !== false }) if (form.schema.length > 0) { await api.generateView(form.name) } if (form.importSample && fileRef.current?.files[0]) { await api.importCSV(form.name, fileRef.current.files[0]) } const updated = await api.getSources() setSources(updated) setSource(form.name) setForm({ name: '', constraint_fields: '', fields: [], schema: [], importSample: true, simplefin_account_id: '' }) setCreating(false) } catch (err) { setCreateError(err.message) } finally { setCreateLoading(false) } } return (

Sources

{!creating && ( )}
{!creating && sources.length === 0 && (

No sources yet. Create one to get started.

)} {!creating && sources.length > 0 && (
{sources.map(s => ( ))}
)} {creating && (

New source

setForm(f => ({ ...f, name: e.target.value }))} placeholder="e.g. chase, dcard" />
{/* Bank feed — optional; picking an account defaults the constraint field to the transaction id, which is what dedupe needs */}
{bridgeAccounts === null ? ( ) : ( )}
{bridgeError &&

{bridgeError}

} {form.simplefin_account_id && sampleInfo && (

Read {sampleInfo.fetched} transaction{sampleInfo.fetched === 1 ? '' : 's'} from this account and found {sampleInfo.fields} field{sampleInfo.fields === 1 ? '' : 's'}. The table below lists what this account actually returns — fields it never sends won’t appear.

{form.constraint_fields === 'id' && (

id is checked as the constraint field because it is SimpleFIN’s own transaction identifier. Syncs pull an overlapping window of days, so the same transaction arrives more than once — matching on id skips the repeats while still keeping genuinely separate charges that share a date, amount, and description.

)} {sampleInfo.fetched === 0 && (

No transactions came back, so there was nothing to infer fields from. Sync first, then set the fields up here.

)}
)}
{form.fields.length > 0 && (
{form.fields.map(f => { const schemaEntry = form.schema.find(s => s.name === f.name) const inView = !!schemaEntry const currentType = schemaEntry?.type || f.type return ( ) })}
Key Type Constraint In view Seq
{f.name} {inView && ( )} s.trim()).includes(f.name)} onChange={e => { const current = form.constraint_fields.split(',').map(s => s.trim()).filter(Boolean) const next = e.target.checked ? [...current, f.name] : current.filter(n => n !== f.name) setForm(ff => ({ ...ff, constraint_fields: next.join(', ') })) }} /> { if (e.target.checked) { const nextSeq = form.schema.length > 0 ? Math.max(...form.schema.map(s => s.seq ?? 0)) + 1 : 1 setForm(ff => ({ ...ff, schema: [...ff.schema, { name: f.name, type: f.type, seq: nextSeq }] })) } else { setForm(ff => ({ ...ff, schema: ff.schema.filter(s => s.name !== f.name) })) } }} /> {inView && ( setForm(ff => ({ ...ff, schema: ff.schema.map(s => s.name === f.name ? { ...s, seq: parseInt(e.target.value) || 0 } : s) }))} /> )}
)} {form.fields.length === 0 && (
setForm(f => ({ ...f, constraint_fields: e.target.value }))} placeholder="e.g. date, amount, description" />
)}
{form.fields.length > 0 && ( )}
{createError &&

{createError}

}
)}
) }