Skip to Content
Components

Data Import Wizard

Multi-step modal wizard that turns an Excel/CSV upload into Kiva data source records — drag-drop, auto-mapped column→field assignment, per-type config, value-renderer preview, and a result summary.

Client Only

Installation

pnpm dlx @kivacore/ui-cli add @kivacore/ui-data-import-wizard
Required Packages(2 packages)
pnpm add @kivacore/api-client @tanstack/react-query

When to Use

Reach for <DataImportWizard> (and the matching useKivaDataImportWizard hook) whenever you want to give end-users a fully-guided "upload XLSX → see results" flow against any Kiva data source. The component is presentational — every prop is a state slice plus a callback — so the smart hook does the heavy lifting (file upload, analyse, auto-mapping, preview, import).

If you only need to import data programmatically, use the hook's imperative helpers (uploadAsync, analyseAsync, importAsync) and ignore the rendered wizard element.

Usage

'use client';

import { useKivaAuth } from '@kivacore/signin';

import { Button } from '@kivacore/ui/primitives/ui/button';
import { useKivaDataImportWizard } from '@kivacore/ui/hooks/use-kiva-data-import-wizard';

export function ContactsImportButton() {
  const { client } = useKivaAuth();

  if (!client) return null;

  const { openWizard, wizard } = useKivaDataImportWizard({
    client,
    appSlug: 'crm',
    dataSourceSlug: 'contact',
    requiredFieldSlugs: ['email']
  });

  return (
    <>
      <Button onClick={openWizard}>Import contacts…</Button>
      {wizard}
    </>
  );
}

Wizard Steps

StepPurpose
UploadDrag-drop / file picker. Validates extension + size client-side, then chains upload → analyse mutations.
Map fieldsOne card per source column. Per type: relation reference_key, phone country code, date format, money/phone companion column. Auto-maps obvious matches.
OptionsToggle "Update existing records on unique-key match" (upsertUniqueFields). Summary tiles for row, column, and unique-field counts.
PreviewRenders the first N rows using useKivaFieldComponent(field.type, 'value-renderer') so every cell looks like it does in <DataGrid>.
ResultTiles for successful records, warnings, duplicates, and errors. Per-row error list. "Import another file" / "Done" actions.

API Reference

<DataImportWizard>

The dumb component. Drive every prop from your own state — typically through useKivaDataImportWizard, which already wires every prop. Only reach for the component directly when you need a custom state machine (e.g. a server-component wrapper).

PropTypeDescription
open / onOpenChangeboolean / (open: boolean) => voidModal open state.
step / onStepChangeImportWizardStep / (step) => voidCurrent step + setter. Steps: upload, mapping, options, preview, progress, result.
targetFieldsReadonlyArray<KivaFieldLike>Fields the user can map to. Supplied by the hook from useKivaDataViewSelect.
requiredFieldSlugsReadonlyArray<string>Slugs that must be mapped before leaving the mapping step.
uniqueFieldSlugsReadonlyArray<string>Slugs covered by unique indexes (drives the upsert toggle).
file / uploadedFile / analysedFile / importResultvariousSnapshots of each phase's payload.
mapping / onMappingChangeWizardMappingMap / (next) => voidPer-source-column mapping state.
upsertUniqueFields / onUpsertChangeboolean / (next) => voidUpsert toggle.
isUploading / isAnalysing / isImportingbooleanMutation pending flags.
uploadError / analyseError / importErrorError | nullPer-phase errors surfaced in the relevant step's banner.
onPickFile / onAnalyse / onConfirmMapping / onConfirmOptions / onStartImport / onReset / onClosecallbacksHook into each step's primary action.
title / description / iconReactNode / ReactNode / stringHeader customization (defaults are translated).
previewRowCountnumberDefault 10.
maxFileSizeBytesnumberDefault 20 * 1024 * 1024 (20 MB).
acceptedExtensionsReadonlyArray<string>Default ['xlsx', 'xls', 'csv'].
classNamestringExtra class for the dialog body.

Components

ComponentDescription
DataImportWizardTop-level shell — composes AwesomeDialog + Stepper + step bodies + footer.
UploadStepStep 1 — drag-drop + file picker + spinners.
MappingStepStep 2 — per-column target select + per-type sub-config.
OptionsStepStep 3 — upsert toggle + summary tiles.
PreviewStepStep 4 — value-renderer-driven preview table.
ProgressStepSteps 5/6 — progress UI + result summary tiles.

Each step component is exported individually so consumers can rearrange or replace them in custom flows.

Helpers

HelperDescription
buildAutoMapping(columns, fields)Greedy slug + name + token-Jaccard matcher. Returns a WizardMappingMap.
inferFieldOptions(field)Default fieldOptions for field-relation, field-phone, and field-date* (matches the import API contract).
inferTargetOptions(targetSlug, field)inferFieldOptions for a field, plus the default date order for a record's reserved created_on, which has no field but is read with the column's date order.
validateMapping(mapping, requiredSlugs)Returns { valid, missing, duplicateTargets }.
buildImportOptions(mapping, fields, upsert, uniqueData?)Converts UI state to the { fieldMapping, fieldOptions, uniqueData, upsertUniqueFields } POST body.
collectUniqueDataLookups(mapping, fields, analysedFile)Identifies columns that benefit from uniqueData pre-resolution.
buildUniqueDataPayload(specs, resolved)Merges pre-resolved matchedId maps with the lookup specs into the final payload entry.
getSecondarySlug(fieldType)Returns '__amount_currency' / '__phone_country' for composite field types.
slugify(value) / normalizeKey(value)Lowercase / kebab-case helpers used by the auto-mapper. normalizeKey strips diacritics and folds the dotless ı, so Kayıt tarihi → kayit_tarihi.
readDateCell(raw, format, kind)Reads a date or date-time cell the way the import does: the column's date order first, then only the fallback forms that keep it (year first with 4 digits, except under YEAR / DAY / MONTH); with no order set, every fallback in the import's order. A value that fits only another order (03/13/2024 under DAY / MONTH / YEAR) is not read, and a date column takes the date as written, ignoring any time → { status: 'read', value }, 'empty', or 'unread'. A date-time value is the importer's wall clock as a local ISO string (an instant when the cell had a zone); a date is local noon of that day, so the tenant formatter's time-zone projection keeps the day. The preview uses it, so 05.03.2024 shows as 5 March under DAY / MONTH / YEAR.
getDateCellKind(targetSlug, fieldType)'date' / 'dateTime' / null for a mapped column; created_on is always a date-time.
isEmptyImportResult(result)true when a result accounts for none of the rows (nothing written, skipped or reported). Reads the counts, never the envelope's success.

Type Exports

TypeDescription
DataImportWizardPropsProps for the top-level component.
ImportWizardStep'upload' | 'mapping' | 'options' | 'preview' | 'progress' | 'result'.
WizardMappingMapRecord<sourceColumn, ColumnMappingState>.
ColumnMappingStatePer-source-column UI mapping: target slug, optional companion column, type-specific fieldOptions.
UploadedFileInfoShape returned by the upload endpoint.
AnalysedFileShape returned by the analyse endpoint (rows, columns, unique-field hints).
ImportPayloadOptionsBody posted to the import endpoint.
ImportResultPayloadResult returned by the import endpoint (success count, errors, duplicates).
MappingValidationResult{ valid, missing, duplicateTargets }.
ReservedTargetSlug'name' | 'description' | 'created_on' | 'autonumber_id'.
UniqueDataLookupSpecHelper type produced by collectUniqueDataLookups.
DateCellKind / DateCellReading'date' | 'dateTime' and the result of readDateCell.

Field-Type Awareness

Like useKivaDataGrid, every field type is handled automatically:

Field typeMapping-step extrasPreview
field-relation, field-relatedField, field-userSelect, field-userMultiSelectreference_key text input (defaults to 'name').Relation chip via RelationValue.
field-phoneDefault country code input (+90 default) + companion column for __phone_country.Phone display.
field-moneyCompanion column select for __amount_currency.Currency formatter.
field-date, field-dateTime, field-dateRangeDAY/MONTH/YEAR ordering select.Cells read with the chosen order (readDateCell), then the tenant-aware date formatter. A cell the order can't read shows its raw text with a warning; a date-time without a zone is the importer's wall clock.
field-enum, field-status, field-select, field-radioGroup, field-multiSelect, field-tagSelectAuto-mapped to the matching slug.Color-coded enum chip.
Reserved (name, description, created_on, autonumber_id)Surfaced in the System group. created_on gets the date order select and pre-fills from created_at, Oluşturma tarihi or Kayıt tarihi.Plain text; created_on as a date-time.

See Also

On this page