Skip to main content

Class: InvoiceBuilder

@arolariu/website


@arolariu/website / data/mocks/invoice / InvoiceBuilder

Class: InvoiceBuilder

Defined in: data/mocks/invoice.ts:95

Fluent builder for creating mock Invoice objects with customizable properties.

Remarks​

Design Pattern: Implements the Builder pattern for flexible object construction.

Default Initialization:

  • Random UUIDs for identifiers
  • Realistic fake data from faker.js
  • Valid currency with code, name, and symbol
  • Empty arrays for items and shared users
  • Non-deleted state (isSoftDeleted: false)
  • GROCERY category as default

Method Chaining: All with*() methods return this for fluent API usage.

Batch Building: Use buildMany() to create multiple instances with same configuration.

Random Data: Use withRandomItems() and withRandomRecipes() for quick test data.

Examples​

// Basic usage
const invoice = new InvoiceBuilder()
.withId("invoice-123")
.withName("Grocery Shopping")
.withCategory(InvoiceCategory.GROCERY)
.build();
// With nested data
const invoice = new InvoiceBuilder()
.withUserIdentifier("user-456")
.withRandomItems(5)
.withRandomRecipes(2)
.withMerchantReference("merchant-789")
.build();
// Batch creation
const invoices = new InvoiceBuilder()
.withCategory(InvoiceCategory.RESTAURANT)
.withRandomItems()
.buildMany(10);

Constructors​

Constructor​

new InvoiceBuilder(): InvoiceBuilder

Defined in: data/mocks/invoice.ts:142

Creates a new InvoiceBuilder with randomized default values.

Returns​

InvoiceBuilder

Remarks​

Initialization Strategy: Uses faker.js to generate realistic random data for all required Invoice fields. This ensures test invoices are immediately valid without requiring manual configuration.

Default Values:

  • id: Random UUIDv4
  • name: Random 3-word sentence
  • description: Random 7-30 word sentence
  • category: InvoiceCategory.GROCERY
  • isSoftDeleted: false (active invoice)
  • items: Empty array (use withRandomItems to populate)
  • possibleRecipes: Empty array (use withRandomRecipes to populate)
  • scans: Single JPEG scan with random URL

Payment Defaults:

  • Random currency (code, name, symbol)
  • Total amount between 10-1000
  • Tax amount between 5-50% of total

Example​

// Create with all random defaults
const invoice = new InvoiceBuilder().build();

// Override specific fields
const customInvoice = new InvoiceBuilder()
.withId("my-id")
.withCategory(InvoiceCategory.FAST_FOOD)
.build();

See​

createInvoiceBuilder for factory function alternative

Properties​

invoice​

private invoice: Invoice

Defined in: data/mocks/invoice.ts:103

Internal invoice state being constructed.

Remarks​

Mutated by with*() methods during builder configuration. A shallow copy is returned by build to prevent external mutation.

Methods​

withId()​

withId(id): this

Defined in: data/mocks/invoice.ts:218

Sets the unique identifier for the invoice.

Parameters​

id​

string

UUID string identifying this invoice. Should be UUIDv4 format.

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Identity Semantics: The ID is the primary key for invoice identity. Two invoices with the same ID are considered the same entity.

Format: Should be a valid UUIDv4 string for consistency with backend. Non-UUID values are accepted for testing flexibility.

Example​

const invoice = new InvoiceBuilder()
.withId("550e8400-e29b-41d4-a716-446655440000")
.build();

See​

Invoice.id


withName()​

withName(name): this

Defined in: data/mocks/invoice.ts:245

Sets the display name for the invoice.

Parameters​

name​

string

Human-readable name or title for the invoice

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

UI Display: This name appears in invoice lists, search results, and as the primary label in invoice cards.

Searchability: Name is indexed for full-text search in the UI.

Example​

const invoice = new InvoiceBuilder()
.withName("Weekly Groceries - Dec 2025")
.build();

See​

NamedEntity.name


withDescription()​

withDescription(description): this

Defined in: data/mocks/invoice.ts:271

Sets a detailed description for the invoice.

Parameters​

description​

string

Long-form description or notes about the invoice

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

UI Display: Description appears in invoice detail views and tooltips. Supports longer text than withName for detailed context.

Searchability: Description is indexed for full-text search.

Example​

const invoice = new InvoiceBuilder()
.withDescription("Monthly grocery shopping at Whole Foods. Includes organic produce and household items.")
.build();

See​

NamedEntity.description


withCreatedAt()​

withCreatedAt(date): this

Defined in: data/mocks/invoice.ts:299

Sets when the invoice was created.

Parameters​

date​

Date

Timestamp of invoice creation (defaults to random past date)

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Audit Trail: Part of the IAuditable contract for entity lifecycle tracking.

Testing Use Case: Useful for testing date-based filtering, sorting, and "created within last X days" queries.

Example​

// Test invoice created exactly 30 days ago
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const invoice = new InvoiceBuilder()
.withCreatedAt(thirtyDaysAgo)
.build();

See​

IAuditable.createdAt


withLastUpdatedAt()​

withLastUpdatedAt(date): this

Defined in: data/mocks/invoice.ts:326

Sets when the invoice was last modified.

Parameters​

date​

Date

Timestamp of last modification (defaults to random recent date)

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Audit Trail: Part of the IAuditable contract for modification tracking.

Sorting: Used for "recently updated" sort order in invoice lists.

Example​

// Test invoice updated today
const invoice = new InvoiceBuilder()
.withLastUpdatedAt(new Date())
.build();

See​

IAuditable.lastUpdatedAt


withUserIdentifier()​

withUserIdentifier(userId): this

Defined in: data/mocks/invoice.ts:353

Sets which user owns this invoice.

Parameters​

userId​

string

UUID of the user who owns this invoice (Clerk user ID in production)

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Authorization: The userIdentifier determines ownership and default access. Only the owner (or shared users) can view/edit the invoice.

Backend Mapping: Maps to the Clerk user ID in production.

Example​

const invoice = new InvoiceBuilder()
.withUserIdentifier("user_2abc123def")
.build();

See​


withSharedWith()​

withSharedWith(userIds): this

Defined in: data/mocks/invoice.ts:387

Sets which users have shared access to this invoice.

Parameters​

userIds​

string[]

Array of user UUID strings with view/edit access

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Access Control:

  • Empty array = private invoice (only owner can access)
  • Special UUID = public invoice (anyone can view)
  • User UUIDs = specific users have view/edit access

Testing Collaboration: Useful for testing multi-user scenarios, shared invoice lists, and permission checks.

Example​

// Private invoice (default)
const privateInvoice = new InvoiceBuilder().withSharedWith([]).build();

// Shared with specific users
const sharedInvoice = new InvoiceBuilder()
.withSharedWith(["user-1", "user-2"])
.build();

See​


withCategory()​

withCategory(category): this

Defined in: data/mocks/invoice.ts:418

Sets the business category classification for the invoice.

Parameters​

category​

InvoiceCategory

Category enum value from InvoiceCategory

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Filtering: Category enables filtering invoices by type in the UI.

Analytics: Used for spending breakdown by category in reports.

AI Analysis: Influences recipe suggestions and merchant detection.

Example​

const groceryInvoice = new InvoiceBuilder()
.withCategory(InvoiceCategory.GROCERY)
.build();

const restaurantInvoice = new InvoiceBuilder()
.withCategory(InvoiceCategory.FAST_FOOD)
.build();

See​

InvoiceCategory for available categories


withScans()​

withScans(scans): this

Defined in: data/mocks/invoice.ts:450

Sets the invoice scans (receipt images/PDFs).

Parameters​

scans​

InvoiceScan[]

Array of InvoiceScan objects representing invoice photos/documents

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Multiple Scans: Supports multiple scans for multi-page receipts or different views (front/back) of the same receipt.

Scan Types: Supports JPEG, PNG, PDF formats via InvoiceScanType.

Storage: Scan locations are CDN URLs pointing to Azure Blob Storage.

Example​

const invoice = new InvoiceBuilder()
.withScans([
{ scanType: InvoiceScanType.JPEG, location: "https://cdn.example.com/scan1.jpg", metadata: {} },
{ scanType: InvoiceScanType.PDF, location: "https://cdn.example.com/scan2.pdf", metadata: {} },
])
.build();

See​


withMerchantReference()​

withMerchantReference(merchantId): this

Defined in: data/mocks/invoice.ts:477

Links the invoice to a specific merchant/store.

Parameters​

merchantId​

string

UUID of the Merchant entity

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Foreign Key: References a Merchant entity in the invoices domain.

AI Detection: Can be populated by AI analysis of receipt content.

Sentinel Value: Guid.Empty indicates unenriched/unknown merchant.

Example​

const invoice = new InvoiceBuilder()
.withMerchantReference("merchant-uuid-here")
.build();

See​

Invoice.merchantReference


withItems()​

withItems(items): this

Defined in: data/mocks/invoice.ts:510

Sets the list of purchased products/line items.

Parameters​

items​

Product[]

Array of Product objects representing purchased items

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Line Items: Each Product represents a single line item on the receipt with name, quantity, unit price, and total price.

AI Extraction: Products are typically extracted by AI from receipt scans.

Recipe Generation: Items are analyzed for possible recipe suggestions.

Example​

const invoice = new InvoiceBuilder()
.withItems([
{ name: "Milk 2%", quantity: 2, price: 3.99, ... },
{ name: "Bread", quantity: 1, price: 2.50, ... },
])
.build();

See​


withPaymentInformation()​

withPaymentInformation(paymentInfo): this

Defined in: data/mocks/invoice.ts:546

Sets payment method and transaction details for the invoice.

Parameters​

paymentInfo​

PaymentInformation

Payment information object or null if unpaid

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Payment Details:

  • Transaction date
  • Payment type (cash, card, etc.)
  • Currency with code, name, symbol
  • Total cost and tax amounts

Null Handling: Pass null to represent an unpaid/pending invoice.

Example​

const invoice = new InvoiceBuilder()
.withPaymentInformation({
transactionDate: new Date(),
paymentType: PaymentType.CreditCard,
currency: { code: "USD", name: "US Dollar", symbol: "$" },
totalCostAmount: 99.99,
totalTaxAmount: 8.50,
})
.build();

See​


withPaymentAmount()​

withPaymentAmount(amount): this

Defined in: data/mocks/invoice.ts:564

Convenience method to set the total payment amount.

Parameters​

amount​

number

Total cost amount for the invoice

Returns​

this

This InvoiceBuilder instance for method chaining

Example​

const invoice = new InvoiceBuilder()
.withPaymentAmount(150.50)
.build();

withTransactionDate()​

withTransactionDate(date): this

Defined in: data/mocks/invoice.ts:582

Convenience method to set the transaction date.

Parameters​

date​

Date

Transaction date for the payment

Returns​

this

This InvoiceBuilder instance for method chaining

Example​

const invoice = new InvoiceBuilder()
.withTransactionDate(new Date("2024-01-15"))
.build();

withPaymentCurrency()​

withPaymentCurrency(currencyCode): this

Defined in: data/mocks/invoice.ts:600

Convenience method to set the payment currency code.

Parameters​

currencyCode​

string

ISO 4217 currency code (e.g., "USD", "EUR", "RON")

Returns​

this

This InvoiceBuilder instance for method chaining

Example​

const invoice = new InvoiceBuilder()
.withPaymentCurrency("USD")
.build();

withPossibleRecipes()​

withPossibleRecipes(recipes): this

Defined in: data/mocks/invoice.ts:641

Sets AI-generated recipe suggestions based on invoice items.

Parameters​

recipes​

Recipe[]

Array of Recipe suggestions from AI analysis

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

AI Feature: Recipes are generated by analyzing purchased ingredients against a recipe database. This is an AI enrichment artifact.

Recipe Structure: Each recipe includes name, complexity level, cooking/prep times, ingredients list, and instructions.

Example​

const invoice = new InvoiceBuilder()
.withPossibleRecipes([
{
name: "Banana Smoothie",
complexity: RecipeComplexity.Easy,
approximateTotalDuration: 5,
cookingTime: 0,
preparationTime: 5,
ingredients: ["banana", "milk", "honey"],
instructions: "Blend all ingredients until smooth.",
description: "Quick and healthy breakfast smoothie.",
referenceForMoreDetails: "https://recipes.example.com/banana-smoothie",
},
])
.build();

See​


withAdditionalMetadata()​

withAdditionalMetadata(metadata): this

Defined in: data/mocks/invoice.ts:676

Sets custom key-value metadata for extensibility.

Parameters​

metadata​

Record<string, string>

Additional properties as string key-value pairs

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Extensibility: Allows storing arbitrary key-value pairs without schema changes. Useful for feature flags, A/B test data, or custom fields.

Type Safety: All values must be strings. Serialize complex objects to JSON strings if needed.

Special Keys: Some keys have special meaning:

  • isImportant: User-marked priority flag
  • requiresAnalysis: Pending AI processing flag

Example​

const invoice = new InvoiceBuilder()
.withAdditionalMetadata({
source: "mobile-app",
importSource: "email-attachment",
customTag: "monthly-expense",
})
.build();

See​

Invoice.additionalMetadata


withRandomItems()​

withRandomItems(count?): this

Defined in: data/mocks/invoice.ts:713

Generates random product items using faker.js for testing.

Parameters​

count?​

number

Number of items to generate. If omitted, random 3-10 items.

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Random Generation: Uses generateRandomProduct to create each item with realistic fake data.

Generated Properties:

  • Random product names and categories
  • Prices between 0.50 and 100.00
  • Quantities between 1 and 10
  • Random allergen information
  • Product codes and metadata

Default Count: When count is omitted, generates between 3-10 items (random selection each time).

Example​

// Generate random count (3-10 items)
const invoice1 = new InvoiceBuilder().withRandomItems().build();

// Generate exactly 5 items
const invoice2 = new InvoiceBuilder().withRandomItems(5).build();

See​


withRandomScans()​

withRandomScans(count?): this

Defined in: data/mocks/invoice.ts:748

Generates random invoice scans using faker.js for testing.

Parameters​

count?​

number

Number of scans to generate. If omitted, random 1-3 scans.

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Scan Types: Randomly selects from JPEG, PNG, or PDF formats.

Generated Properties:

  • Random scan type from InvoiceScanType
  • Fake image URL (800x600) for location
  • Empty metadata object

Default Count: When count is omitted, generates between 1-3 scans.

Example​

// Generate random count (1-3 scans)
const invoice1 = new InvoiceBuilder().withRandomScans().build();

// Generate exactly 2 scans
const invoice2 = new InvoiceBuilder().withRandomScans(2).build();

See​


withRandomRecipes()​

withRandomRecipes(count?): this

Defined in: data/mocks/invoice.ts:794

Generates random recipe suggestions using faker.js for testing.

Parameters​

count?​

number

Number of recipes to generate. If omitted, random 0-3 recipes.

Returns​

this

This InvoiceBuilder instance for method chaining

Remarks​

Generated Properties:

  • Fake recipe name (3-word sentence)
  • Random complexity from RecipeComplexity
  • Cooking and preparation times (5-120 minutes each)
  • Approximate total duration (total time)
  • Fake description and instructions
  • Reference URL for more details
  • Empty ingredients array (use for testing display, not validation)

Default Count: When count is omitted, generates between 0-3 recipes. Zero recipes simulates invoices without recipe suggestions.

Example​

// Generate random count (0-3 recipes)
const invoice1 = new InvoiceBuilder().withRandomRecipes().build();

// Generate exactly 2 recipes
const invoice2 = new InvoiceBuilder().withRandomRecipes(2).build();

// No recipes (simulating unanalyzed invoice)
const invoice3 = new InvoiceBuilder().withRandomRecipes(0).build();

See​


build()​

build(): Invoice

Defined in: data/mocks/invoice.ts:838

Constructs the final invoice object from builder state.

Returns​

Invoice

The constructed Invoice object ready for use

Remarks​

Shallow Copy: Creates a shallow copy of the internal invoice state. Nested objects (items, scans, recipes) are shared references.

Immutability: The returned invoice should be treated as immutable. Modifications to the returned object do not affect the builder state.

Reusability: The builder can be reused after calling build(). Each call returns a new invoice instance.

Example​

const builder = new InvoiceBuilder().withName("Test");

const invoice1 = builder.build();
const invoice2 = builder.withId("new-id").build();

// invoice1 and invoice2 are separate objects
console.log(invoice1.id !== invoice2.id); // true

See​

buildMany for creating multiple instances


buildMany()​

buildMany(count): Invoice[]

Defined in: data/mocks/invoice.ts:875

Creates multiple invoice instances with identical configuration.

Parameters​

count​

number

How many invoice copies to create. Must be positive integer.

Returns​

Invoice[]

Array of Invoice objects with same configuration

Remarks​

Same Configuration: All invoices share the same property values, including IDs. This is useful for testing scenarios requiring identical test data.

Unique IDs Warning: For invoices with unique IDs, use generateRandomInvoices instead, which generates fresh random data for each invoice.

Shallow Copies: Each invoice is a separate object (via build()), but nested arrays reference the same objects.

Example​

// Create 5 invoices with same configuration
const invoices = new InvoiceBuilder()
.withCategory(InvoiceCategory.GROCERY)
.withUserIdentifier("test-user")
.buildMany(5);

// All have same category and user
invoices.every(inv => inv.category === InvoiceCategory.GROCERY); // true

See​

// was this page useful?