Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

2.2 KB
Raw Blame
export const documentTypes = [
  { value: 'txt', label: 'Plain text (.txt)', mimeType: 'text/plain' },
  { value: 'md', label: 'Markdown (.md)', mimeType: 'text/markdown' },
  { value: 'csv', label: 'Spreadsheet (.csv)', mimeType: 'text/csv' },
] as const;

export type DocumentType = (typeof documentTypes)[number]['value'];

export const MAX_GENERATED_DOCUMENTS = 100;

export function isValidDocumentAmount(amount: number) {
  return Number.isInteger(amount) && amount >= 1 && amount <= MAX_GENERATED_DOCUMENTS;
}

const companies = ['Acme Studio', 'Northwind Labs', 'Evergreen Partners', 'Bluebird Works'];
const subjects = ['Office supplies', 'Design services', 'Software subscription', 'Travel expenses'];

export function generateDocuments({
  type = 'txt',
  amount = 1,
}: {
  type?: DocumentType;
  amount?: number;
} = {}): File[] {
  if (!isValidDocumentAmount(amount)) {
    throw new Error(`Choose between 1 and ${MAX_GENERATED_DOCUMENTS} documents.`);
  }

  const documentType = documentTypes.find(({ value }) => value === type);

  if (!documentType) {
    throw new Error('Unsupported document type.');
  }

  return Array.from({ length: amount }, () => {
    const id = crypto.randomUUID();
    const company = companies[Math.floor(Math.random() * companies.length)];
    const subject = subjects[Math.floor(Math.random() * subjects.length)];
    const total = (10 + Math.random() * 1990).toFixed(2);
    const date = new Date(Date.now() - Math.floor(Math.random() * 365) * 86_400_000)
      .toISOString()
      .slice(0, 10);
    const title = `${company} - ${subject}`;
    const note = 'Generated by Papra devtools for development and testing. Not a real invoice.';

    const content = {
      txt: `${title}\n\nReference: ${id}\nDate: ${date}\nTotal: EUR ${total}\n\n${note}\n`,
      md: `# ${title}\n\n- Reference: ${id}\n- Date: ${date}\n- Total: EUR ${total}\n\n${note}\n`,
      csv: `reference,company,subject,date,currency,total,note\n${id},${company},${subject},${date},EUR,${total},${note}\n`,
    }[type];

    return new File(
      [content],
      `dev-${subject.toLowerCase().replaceAll(' ', '-')}-${Math.random().toString(36).substring(2, 6)}.${type}`,
      {
        type: documentType.mimeType,
      },
    );
  });
}