Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Linear ticket CSV import (#949)

Peter Chinmand95e15b269b2
diff --git a/js/app/packages/app/component/import-linear/ImportLinear.tsx b/js/app/packages/app/component/import-linear/ImportLinear.tsx
new file mode 100644
index 0000000000..1e8e3e5cf8
--- /dev/null
+++ b/js/app/packages/app/component/import-linear/ImportLinear.tsx
@@ -0,0 +1,371 @@
+import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';
+import { toast } from '@core/component/Toast/Toast';
+import { parseCsv } from '@core/util/csv';
+import { createTask } from '@core/util/create';
+import { linearCsvRecordToMacroTaskDraft } from '@core/util/linearImport';
+import { buildSimpleEntityUrl } from '@core/util/url';
+import {
+ queryKeys,
+ useQueryClient as useEntityQueryClient,
+} from '@macro-entity';
+import { useUpsertToHistoryMutation } from '@queries/history/history';
+import { useContacts } from '@core/user';
+import { Button } from '@ui/components/Button';
+import { createEffect, createMemo, createSignal, For, Show } from 'solid-js';
+import { createStore, reconcile } from 'solid-js/store';
+
+type ImportProgress =
+ | { type: 'idle' }
+ | { type: 'running'; done: number; total: number }
+ | { type: 'done'; created: number; skipped: number; failed: number };
+
+function normalize(s: string): string {
+ return s.trim();
+}
+
+function lower(s: string): string {
+ return normalize(s).toLowerCase();
+}
+
+export default function ImportLinear() {
+ const contacts = useContacts();
+ const upsertToHistory = useUpsertToHistoryMutation();
+ const entityQueryClient = useEntityQueryClient();
+
+ const [fileName, setFileName] = createSignal<string>('');
+ const [parseError, setParseError] = createSignal<string>('');
+ const [records, setRecords] = createSignal<readonly Record<string, string>[]>(
+ []
+ );
+ const [assigneeMapping, setAssigneeMapping] = createStore<
+ Record<string, string>
+ >({});
+ const [createdIds, setCreatedIds] = createSignal<readonly string[]>([]);
+ const [progress, setProgress] = createSignal<ImportProgress>({
+ type: 'idle',
+ });
+ const [isImporting, setIsImporting] = createSignal(false);
+
+ const runningProgress = createMemo(() => {
+ const p = progress();
+ return p.type === 'running' ? p : null;
+ });
+
+ const doneProgress = createMemo(() => {
+ const p = progress();
+ return p.type === 'done' ? p : null;
+ });
+
+ const uniqueAssignees = createMemo(() => {
+ const set = new Set<string>();
+ for (const r of records()) {
+ const a = normalize(r['Assignee'] ?? '');
+ if (a) set.add(a);
+ }
+ return [...set].sort((a, b) => a.localeCompare(b));
+ });
+
+ const contactOptions = createMemo(() => {
+ const cs = contacts();
+ return cs
+ .map((c) => ({
+ id: c.id,
+ label:
+ c.name && c.name !== c.email ? `${c.name} (${c.email})` : c.email,
+ email: c.email,
+ name: c.name,
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label));
+ });
+
+ createEffect(() => {
+ // Auto-map assignees when possible based on email/name match.
+ const current = uniqueAssignees();
+ const options = contactOptions();
+
+ for (const a of current) {
+ if (assigneeMapping[a] !== undefined) continue;
+
+ const aLower = lower(a);
+ const mapped = a.includes('@')
+ ? options.find((o) => lower(o.email) === aLower)
+ : options.find((o) => lower(o.name) === aLower);
+
+ setAssigneeMapping(a, mapped?.id ?? '');
+ }
+ });
+
+ const previewDrafts = createMemo(() => {
+ const allRows = records();
+
+ const allDrafts = allRows.map((r, index) => {
+ const assigneeRaw = normalize(r['Assignee'] ?? '');
+ const assigneeUserId = assigneeRaw ? assigneeMapping[assigneeRaw] : '';
+ return {
+ rowNum: index + 1,
+ ...linearCsvRecordToMacroTaskDraft({
+ record: r,
+ assigneeUserId: assigneeUserId ? assigneeUserId : null,
+ }),
+ };
+ });
+
+ // Show first 20 plus any additional rows with warnings
+ return allDrafts.filter((d, i) => i < 20 || d.warnings.length > 0);
+ });
+
+ const handleFileChange = async (file: File | undefined) => {
+ setCreatedIds([]);
+ setProgress({ type: 'idle' });
+ setParseError('');
+ setRecords([]);
+
+ if (!file) {
+ setFileName('');
+ return;
+ }
+
+ setFileName(file.name);
+ const text = await file.text();
+ const result = parseCsv(text);
+ if (!result.ok) {
+ setParseError(result.error);
+ return;
+ }
+
+ // Linear exports use quoted headers; our parser returns them unquoted already.
+ setRecords(result.records);
+ };
+
+ const canImport = () =>
+ records().length > 0 && !parseError() && !isImporting();
+
+ const runImport = async () => {
+ const rows = records();
+ if (rows.length === 0) return;
+
+ setIsImporting(true);
+ setCreatedIds([]);
+ setProgress({ type: 'running', done: 0, total: rows.length });
+
+ let created = 0;
+ let skipped = 0;
+ let failed = 0;
+ const createdList: string[] = [];
+
+ try {
+ for (let i = 0; i < rows.length; i++) {
+ const r = rows[i];
+ const assigneeRaw = normalize(r['Assignee'] ?? '');
+ const assigneeUserId = assigneeRaw ? assigneeMapping[assigneeRaw] : '';
+
+ const draft = linearCsvRecordToMacroTaskDraft({
+ record: r,
+ assigneeUserId: assigneeUserId ? assigneeUserId : null,
+ });
+
+ if (!draft.title) {
+ skipped++;
+ setProgress({ type: 'running', done: i + 1, total: rows.length });
+ continue;
+ }
+
+ const id = await createTask({
+ title: draft.title,
+ content: draft.content,
+ propertyValues: draft.propertyValues,
+ });
+
+ if (!id) {
+ failed++;
+ } else {
+ created++;
+ createdList.push(id);
+ upsertToHistory.mutate({ itemId: id, itemType: 'document' });
+ }
+
+ setProgress({ type: 'running', done: i + 1, total: rows.length });
+ }
+
+ // Refresh DSS-backed lists so the new tasks appear.
+ entityQueryClient.invalidateQueries({ queryKey: queryKeys.all.dss });
+
+ setCreatedIds(createdList);
+ setProgress({ type: 'done', created, skipped, failed });
+ toast.success(`Imported ${created} tasks`);
+ if (failed > 0) toast.failure(`${failed} tasks failed to import`);
+ } finally {
+ setIsImporting(false);
+ }
+ };
+
+ return (
+ <div class="flex flex-col h-full w-full">
+ <div class="flex-1 overflow-y-auto p-4 flex flex-col gap-4">
+ <div class="flex items-center justify-between">
+ <div class="text-lg font-medium text-ink">Import Linear CSV</div>
+ <DeprecatedTextButton
+ theme="base"
+ text="Clear"
+ onClick={() => {
+ setFileName('');
+ setParseError('');
+ setRecords([]);
+ setCreatedIds([]);
+ setProgress({ type: 'idle' });
+ setAssigneeMapping(reconcile({}));
+ }}
+ />
+ </div>
+
+ <div class="flex flex-col gap-2">
+ <label class="text-sm text-ink-muted">CSV file</label>
+ <label class="inline-flex items-center gap-2 px-4 py-2 bg-accent text-accent-contrast font-medium rounded-md cursor-pointer hover:bg-accent-hover transition-colors w-fit">
+ <span>Choose File</span>
+ <input
+ type="file"
+ accept=".csv,text/csv"
+ onChange={(e) => handleFileChange(e.currentTarget.files?.[0])}
+ class="sr-only"
+ />
+ </label>
+ <Show when={fileName()}>
+ <div class="text-sm text-ink">
+ <span class="text-ink-muted">Loaded:</span> {fileName()}
+ </div>
+ </Show>
+ <Show when={parseError()}>
+ <div class="text-sm text-failure-ink">{parseError()}</div>
+ </Show>
+ </div>
+
+ <Show when={records().length > 0}>
+ <div class="flex flex-col gap-2">
+ <div class="text-sm text-ink-muted">
+ Rows: <span class="text-ink">{records().length}</span>
+ </div>
+
+ <Show when={uniqueAssignees().length > 0}>
+ <div class="flex flex-col gap-2">
+ <div class="text-sm font-medium text-ink">Assignee mapping</div>
+ <div class="text-xs text-ink-muted">
+ Linear assignees that don’t match your contacts will import as
+ unassigned unless you map them here.
+ </div>
+
+ <div class="flex flex-col gap-2 border border-edge rounded-sm p-2">
+ <For each={uniqueAssignees()}>
+ {(assignee) => (
+ <div class="flex items-center gap-3">
+ <div class="flex-1 min-w-0">
+ <div class="text-sm text-ink truncate">
+ {assignee}
+ </div>
+ </div>
+ <select
+ class="text-sm bg-menu border border-edge rounded-xs px-2 py-1"
+ value={assigneeMapping[assignee] ?? ''}
+ onChange={(e) =>
+ setAssigneeMapping(assignee, e.currentTarget.value)
+ }
+ >
+ <option value="">Unassigned</option>
+ <For each={contactOptions()}>
+ {(o) => <option value={o.id}>{o.label}</option>}
+ </For>
+ </select>
+ </div>
+ )}
+ </For>
+ </div>
+ </div>
+ </Show>
+ </div>
+ </Show>
+
+ <Show when={records().length > 0}>
+ <div class="flex flex-col gap-2">
+ <div class="text-sm font-medium text-ink">
+ Preview (first 20 + all rows with warnings)
+ </div>
+ <div class="border border-edge rounded-sm overflow-hidden">
+ <table class="w-full text-sm">
+ <thead class="bg-hover">
+ <tr class="text-left">
+ <th class="p-2">Row</th>
+ <th class="p-2">Title</th>
+ <th class="p-2">Warnings</th>
+ </tr>
+ </thead>
+ <tbody>
+ <For each={previewDrafts()}>
+ {(d) => (
+ <tr class="border-t border-edge">
+ <td class="p-2 align-top">
+ <div class="text-ink-muted">{d.rowNum}</div>
+ </td>
+ <td class="p-2 align-top">
+ <div class="text-ink">
+ {d.title || '(missing title)'}
+ </div>
+ </td>
+ <td class="p-2 align-top">
+ <div class="text-xs text-ink-muted">
+ {d.warnings.length > 0
+ ? d.warnings.join(' · ')
+ : '—'}
+ </div>
+ </td>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </Show>
+
+ <Show when={createdIds().length > 0}>
+ <div class="flex flex-col gap-2">
+ <div class="text-sm font-medium text-ink">Created tasks</div>
+ <div class="flex flex-col gap-1">
+ <For each={createdIds()}>
+ {(id) => (
+ <a
+ class="text-sm text-ink underline underline-offset-2"
+ href={buildSimpleEntityUrl({ type: 'task', id }, {})}
+ target="_blank"
+ rel="noreferrer"
+ >
+ {id}
+ </a>
+ )}
+ </For>
+ </div>
+ </div>
+ </Show>
+ </div>
+
+ <div class="border-t border-edge p-4 flex items-center gap-3 shrink-0">
+ <Button onClick={runImport} disabled={!canImport()}>
+ Import tasks
+ </Button>
+ <Show when={runningProgress()}>
+ {(p) => (
+ <div class="text-sm text-ink-muted">
+ Importing… {p().done}/{p().total}
+ </div>
+ )}
+ </Show>
+ <Show when={doneProgress()}>
+ {(p) => (
+ <div class="text-sm text-ink-muted">
+ Done — created {p().created}, skipped {p().skipped}, failed{' '}
+ {p().failed}
+ </div>
+ )}
+ </Show>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsx
index 4692b5e59e..00e3a4e3da 100644
--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx
+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx
@@ -60,6 +60,10 @@ registerComponent('loading', () => <LoadingBlock />);
registerComponent('channel-compose', () => <ChannelCompose />);
registerComponent('email-compose', () => <EmailCompose />);
registerComponent('task-compose', () => <ComposeTask />);
+registerComponent(
+ 'import-linear',
+ lazy(() => import('@app/component/import-linear/ImportLinear'))
+);
registerComponent('settings', () => <SettingsPanel />);
registerComponent('notification', () => <NotificationRoute />);
diff --git a/js/app/packages/core/util/csv.test.ts b/js/app/packages/core/util/csv.test.ts
new file mode 100644
index 0000000000..3004e18331
--- /dev/null
+++ b/js/app/packages/core/util/csv.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from 'vitest';
+import { parseCsv } from './csv';
+
+describe('parseCsv', () => {
+ test('parses a simple CSV with headers', () => {
+ const res = parseCsv('a,b\n1,2\n3,4\n');
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.headers).toEqual(['a', 'b']);
+ expect(res.records).toEqual([
+ { a: '1', b: '2' },
+ { a: '3', b: '4' },
+ ]);
+ });
+
+ test('handles quoted commas and escaped quotes', () => {
+ const res = parseCsv('a,b\n"hello, world","he said ""hi"""\n');
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.records).toEqual([{ a: 'hello, world', b: 'he said "hi"' }]);
+ });
+
+ test('handles newlines inside quotes', () => {
+ const res = parseCsv('a,b\n"line1\nline2",x\n');
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.records).toEqual([{ a: 'line1\nline2', b: 'x' }]);
+ });
+
+ test('errors on unterminated quote', () => {
+ const res = parseCsv('a\n"oops\n');
+ expect(res.ok).toBe(false);
+ if (res.ok) return;
+ expect(res.error).toContain('unterminated');
+ });
+});
diff --git a/js/app/packages/core/util/csv.ts b/js/app/packages/core/util/csv.ts
new file mode 100644
index 0000000000..53a08174c4
--- /dev/null
+++ b/js/app/packages/core/util/csv.ts
@@ -0,0 +1,115 @@
+export type CsvParseResult<TRecord extends Record<string, string>> =
+ | {
+ ok: true;
+ headers: readonly string[];
+ records: readonly TRecord[];
+ }
+ | {
+ ok: false;
+ error: string;
+ };
+
+function normalizeNewlines(text: string): string {
+ // Normalize Windows newlines to Unix so we only have to handle \n.
+ return text.replaceAll('\r\n', '\n').replaceAll('\r', '\n');
+}
+
+/**
+ * Parse a CSV string supporting:
+ * - Comma delimiters
+ * - Double-quoted fields (with escaped quotes via "" inside quoted fields)
+ * - Newlines inside quoted fields
+ *
+ * This is intentionally small + dependency-free for environments where we
+ * can't add new packages.
+ */
+export function parseCsv(
+ csvText: string
+): CsvParseResult<Record<string, string>> {
+ const text = normalizeNewlines(csvText);
+ if (!text.trim()) return { ok: false, error: 'CSV is empty' };
+
+ const rows: string[][] = [];
+ let row: string[] = [];
+ let field = '';
+ let inQuotes = false;
+
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+
+ if (inQuotes) {
+ if (ch === '"') {
+ const next = text[i + 1];
+ if (next === '"') {
+ field += '"';
+ i++;
+ continue;
+ }
+ inQuotes = false;
+ continue;
+ }
+
+ field += ch;
+ continue;
+ }
+
+ if (ch === '"') {
+ // Start of quoted field.
+ inQuotes = true;
+ continue;
+ }
+
+ if (ch === ',') {
+ row.push(field);
+ field = '';
+ continue;
+ }
+
+ if (ch === '\n') {
+ row.push(field);
+ field = '';
+ // Skip trailing completely-empty rows (e.g. final newline).
+ if (!(row.length === 1 && row[0] === '' && rows.length > 0)) {
+ rows.push(row);
+ }
+ row = [];
+ continue;
+ }
+
+ field += ch;
+ }
+
+ if (inQuotes) return { ok: false, error: 'CSV has an unterminated quote' };
+
+ // Flush the last field/row (common when file does not end with newline).
+ row.push(field);
+ if (!(row.length === 1 && row[0] === '' && rows.length > 0)) {
+ rows.push(row);
+ }
+
+ const headerRow = rows[0];
+ if (!headerRow || headerRow.length === 0) {
+ return { ok: false, error: 'CSV is missing a header row' };
+ }
+
+ const headers = headerRow.map((h) => h.trim());
+ if (headers.some((h) => h.length === 0)) {
+ return { ok: false, error: 'CSV contains an empty header column' };
+ }
+
+ const dataRows = rows.slice(1);
+ const records: Record<string, string>[] = [];
+ for (const r of dataRows) {
+ // Pad short rows and ignore extra columns.
+ const padded = [...r];
+ while (padded.length < headers.length) padded.push('');
+
+ const record: Record<string, string> = {};
+ for (let i = 0; i < headers.length; i++) {
+ record[headers[i] ?? ''] = padded[i] ?? '';
+ }
+ records.push(record);
+ }
+
+ return { ok: true, headers, records };
+}
diff --git a/js/app/packages/core/util/linearImport.test.ts b/js/app/packages/core/util/linearImport.test.ts
new file mode 100644
index 0000000000..5b7deb97d6
--- /dev/null
+++ b/js/app/packages/core/util/linearImport.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, test } from 'vitest';
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '../component/Properties/constants';
+import { linearCsvRecordToMacroTaskDraft } from './linearImport';
+
+describe('linearCsvRecordToMacroTaskDraft', () => {
+ test('maps Completed timestamp to completed status', () => {
+ const draft = linearCsvRecordToMacroTaskDraft({
+ record: {
+ Title: 'A',
+ Completed: '2025-01-01',
+ Status: 'In Progress',
+ },
+ assigneeUserId: null,
+ });
+
+ const status = draft.propertyValues.find(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.STATUS
+ );
+ expect(status).toBeTruthy();
+ expect(status?.value).toEqual({
+ type: 'select_option',
+ option_id: PROPERTY_OPTION_IDS.STATUS.COMPLETED,
+ });
+ });
+
+ test('maps Archived timestamp to canceled status (best available option)', () => {
+ const draft = linearCsvRecordToMacroTaskDraft({
+ record: {
+ Title: 'A',
+ Archived: '2025-01-02',
+ Status: 'Done',
+ },
+ assigneeUserId: null,
+ });
+
+ const status = draft.propertyValues.find(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.STATUS
+ );
+ expect(status?.value).toEqual({
+ type: 'select_option',
+ option_id: PROPERTY_OPTION_IDS.STATUS.CANCELED,
+ });
+
+ expect(draft.content).toContain('Linear Archived: 2025-01-02');
+ });
+
+ test('maps priority strings', () => {
+ const draft = linearCsvRecordToMacroTaskDraft({
+ record: {
+ Title: 'A',
+ Priority: 'Urgent',
+ },
+ assigneeUserId: null,
+ });
+ const priority = draft.propertyValues.find(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.PRIORITY
+ );
+ expect(priority?.value).toEqual({
+ type: 'select_option',
+ option_id: PROPERTY_OPTION_IDS.PRIORITY.URGENT,
+ });
+ });
+
+ test('maps priority numeric values', () => {
+ const draft = linearCsvRecordToMacroTaskDraft({
+ record: {
+ Title: 'A',
+ Priority: '2',
+ },
+ assigneeUserId: null,
+ });
+ const priority = draft.propertyValues.find(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.PRIORITY
+ );
+ expect(priority?.value).toEqual({
+ type: 'select_option',
+ option_id: PROPERTY_OPTION_IDS.PRIORITY.HIGH,
+ });
+ });
+});
diff --git a/js/app/packages/core/util/linearImport.ts b/js/app/packages/core/util/linearImport.ts
new file mode 100644
index 0000000000..4f44003190
--- /dev/null
+++ b/js/app/packages/core/util/linearImport.ts
@@ -0,0 +1,205 @@
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@core/component/Properties/constants';
+import { EntityType } from '@service-storage/generated/schemas/entityType';
+import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';
+
+export const LINEAR_CSV_HEADERS = {
+ title: 'Title',
+ description: 'Description',
+ status: 'Status',
+ priority: 'Priority',
+ assignee: 'Assignee',
+ completed: 'Completed',
+ canceled: 'Canceled',
+ archived: 'Archived',
+ id: 'ID',
+ uuid: 'UUID',
+ team: 'Team',
+ updated: 'Updated',
+ created: 'Created',
+} as const;
+
+type StatusOptionId =
+ (typeof PROPERTY_OPTION_IDS.STATUS)[keyof typeof PROPERTY_OPTION_IDS.STATUS];
+
+type PriorityOptionId =
+ (typeof PROPERTY_OPTION_IDS.PRIORITY)[keyof typeof PROPERTY_OPTION_IDS.PRIORITY];
+
+function normalizeText(s: string | undefined): string {
+ return (s ?? '').trim();
+}
+
+function lower(s: string | undefined): string {
+ return normalizeText(s).toLowerCase();
+}
+
+function hasValue(s: string | undefined): boolean {
+ return normalizeText(s).length > 0;
+}
+
+function parseLinearPriority(
+ value: string | undefined
+): PriorityOptionId | null {
+ const raw = normalizeText(value);
+ if (!raw) return null;
+
+ const asNum = Number(raw);
+ if (Number.isFinite(asNum)) {
+ // Linear exports priority as 0-4 in some formats:
+ // 0 = none, 1 = urgent, 2 = high, 3 = medium, 4 = low
+ switch (Math.trunc(asNum)) {
+ case 1:
+ return PROPERTY_OPTION_IDS.PRIORITY.URGENT;
+ case 2:
+ return PROPERTY_OPTION_IDS.PRIORITY.HIGH;
+ case 3:
+ return PROPERTY_OPTION_IDS.PRIORITY.MEDIUM;
+ case 4:
+ return PROPERTY_OPTION_IDS.PRIORITY.LOW;
+ default:
+ return null;
+ }
+ }
+
+ const p = raw.toLowerCase();
+ if (p.includes('urgent')) return PROPERTY_OPTION_IDS.PRIORITY.URGENT;
+ if (p.includes('high')) return PROPERTY_OPTION_IDS.PRIORITY.HIGH;
+ if (p.includes('medium') || p === 'med')
+ return PROPERTY_OPTION_IDS.PRIORITY.MEDIUM;
+ if (p.includes('low')) return PROPERTY_OPTION_IDS.PRIORITY.LOW;
+ if (p.includes('no priority') || p.includes('none')) return null;
+
+ return null;
+}
+
+function parseLinearStatusOptionId(args: {
+ status: string | undefined;
+ completed: string | undefined;
+ canceled: string | undefined;
+ archived: string | undefined;
+}): StatusOptionId {
+ // Timestamps override the status label when present.
+ if (hasValue(args.archived) || hasValue(args.canceled)) {
+ return PROPERTY_OPTION_IDS.STATUS.CANCELED;
+ }
+ if (hasValue(args.completed)) {
+ return PROPERTY_OPTION_IDS.STATUS.COMPLETED;
+ }
+
+ const s = lower(args.status);
+
+ if (s.includes('cancel')) return PROPERTY_OPTION_IDS.STATUS.CANCELED;
+ if (s.includes('done') || s.includes('complete'))
+ return PROPERTY_OPTION_IDS.STATUS.COMPLETED;
+ if (s.includes('review')) return PROPERTY_OPTION_IDS.STATUS.IN_REVIEW;
+ if (
+ s.includes('progress') ||
+ s.includes('doing') ||
+ s.includes('started') ||
+ s.includes('in dev')
+ ) {
+ return PROPERTY_OPTION_IDS.STATUS.IN_PROGRESS;
+ }
+ return PROPERTY_OPTION_IDS.STATUS.NOT_STARTED;
+}
+
+export type MacroTaskDraft = {
+ title: string;
+ content: string;
+ propertyValues: PropertyInput[];
+ warnings: readonly string[];
+};
+
+export function linearCsvRecordToMacroTaskDraft(args: {
+ record: Record<string, string>;
+ assigneeUserId?: string | null;
+}): MacroTaskDraft {
+ const record = args.record;
+ const title = normalizeText(record[LINEAR_CSV_HEADERS.title]);
+ const description = normalizeText(record[LINEAR_CSV_HEADERS.description]);
+
+ const statusOptionId = parseLinearStatusOptionId({
+ status: record[LINEAR_CSV_HEADERS.status],
+ completed: record[LINEAR_CSV_HEADERS.completed],
+ canceled: record[LINEAR_CSV_HEADERS.canceled],
+ archived: record[LINEAR_CSV_HEADERS.archived],
+ });
+
+ const priorityOptionId = parseLinearPriority(
+ record[LINEAR_CSV_HEADERS.priority]
+ );
+
+ const warnings: string[] = [];
+ if (!title) warnings.push('Missing Title');
+
+ const propertyValues: PropertyInput[] = [
+ {
+ propertyId: SYSTEM_PROPERTY_IDS.STATUS,
+ value: {
+ type: 'select_option',
+ option_id: statusOptionId,
+ },
+ },
+ ];
+
+ if (priorityOptionId) {
+ propertyValues.push({
+ propertyId: SYSTEM_PROPERTY_IDS.PRIORITY,
+ value: {
+ type: 'select_option',
+ option_id: priorityOptionId,
+ },
+ });
+ }
+
+ if (args.assigneeUserId) {
+ propertyValues.push({
+ propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ value: {
+ type: 'multi_entity_reference',
+ references: [
+ {
+ entity_id: args.assigneeUserId,
+ entity_type: EntityType.USER,
+ },
+ ],
+ },
+ });
+ } else if (hasValue(record[LINEAR_CSV_HEADERS.assignee])) {
+ warnings.push(
+ `Assignee not mapped: ${record[LINEAR_CSV_HEADERS.assignee]}`
+ );
+ }
+
+ const meta: string[] = [];
+ const id = normalizeText(record[LINEAR_CSV_HEADERS.id]);
+ const uuid = normalizeText(record[LINEAR_CSV_HEADERS.uuid]);
+ const team = normalizeText(record[LINEAR_CSV_HEADERS.team]);
+ const created = normalizeText(record[LINEAR_CSV_HEADERS.created]);
+ const updated = normalizeText(record[LINEAR_CSV_HEADERS.updated]);
+ const originalStatus = normalizeText(record[LINEAR_CSV_HEADERS.status]);
+ const originalPriority = normalizeText(record[LINEAR_CSV_HEADERS.priority]);
+ const completed = normalizeText(record[LINEAR_CSV_HEADERS.completed]);
+ const canceled = normalizeText(record[LINEAR_CSV_HEADERS.canceled]);
+ const archived = normalizeText(record[LINEAR_CSV_HEADERS.archived]);
+
+ if (team) meta.push(`- Team: ${team}`);
+ if (id) meta.push(`- Linear ID: ${id}`);
+ if (uuid) meta.push(`- Linear UUID: ${uuid}`);
+ if (originalStatus) meta.push(`- Linear Status: ${originalStatus}`);
+ if (originalPriority) meta.push(`- Linear Priority: ${originalPriority}`);
+ if (created) meta.push(`- Linear Created: ${created}`);
+ if (updated) meta.push(`- Linear Updated: ${updated}`);
+ if (completed) meta.push(`- Linear Completed: ${completed}`);
+ if (canceled) meta.push(`- Linear Canceled: ${canceled}`);
+ if (archived) meta.push(`- Linear Archived: ${archived}`);
+
+ const content =
+ meta.length > 0
+ ? `${description}\n\n---\nImported from Linear\n${meta.join('\n')}`.trim()
+ : description;
+
+ return { title, content, propertyValues, warnings };
+}