### Budgie Project Development and Build Scripts Source: https://context7.com/zazagdev/budgie/llms.txt This section lists common npm scripts for managing the Budgie project. It includes commands for starting the development server, building for production, watching for changes, and formatting code using Prettier. These scripts facilitate development, testing, and deployment workflows. ```bash # Start development server npm start # Runs: ng serve # Access: http://localhost:4200 # Features: Hot reload, source maps, debugging enabled # Production build npm run build # Runs: ng build # Output: dist/ directory # Features: Minification, tree-shaking, hashing, optimization # Watch mode (continuous build) npm run watch # Runs: ng build --watch --configuration development # Use case: Development with external tools # Format code npm run format # Runs: prettier --write . # Formats all TypeScript, HTML, SCSS, JSON files # Format check (CI/CD) npm run format:check # Runs: prettier --check . # Exit code 1 if formatting needed # Format staged files (pre-commit) npm run format:staged # Runs: pretty-quick --staged # Only formats Git staged files # Run tests npm test # Runs: ng test # Framework: Jasmine + Karma ``` -------------------------------- ### Transaction Service with LocalStorage (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt An example implementation of a `TransactionService` that utilizes the `StorageLayer` for persisting transaction data. It demonstrates asynchronous operations for fetching and adding transactions, integrating the `generateUID` function for new transaction IDs. It relies on the `StorageLayer` and the `generateUID` utility. The `delay` function is a placeholder for actual async operations. ```typescript export class TransactionService { async getAll(): Promise { await this.delay(Math.random() * 250); const transactions = StorageLayer.loadTransactions(); this._transactions.set(transactions); return transactions; } async add(transaction: TransactionRaw): Promise { await this.delay(Math.random() * 250); const transactionWithId: Transaction = { ...transaction, date: new Date(), id: generateUID(), }; const updated = [...this._transactions(), transactionWithId]; this._transactions.set(updated); StorageLayer.saveTransactions(updated); return transactionWithId; } } ``` -------------------------------- ### Angular Income vs Expenses Chart Example (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code demonstrates how to use the StackedColumnChartComponent in an Angular application to visualize income versus expenses. It utilizes signals and computed properties for managing timeframes and chart data, with a dependency on a TransactionService. The component displays buttons for time frame selection and integrates the chart component. ```typescript // Usage example (src/app/components/charts/specific/transactions-column-chart/) import { Component, computed, inject, signal } from '@angular/core'; @Component({ selector: 'income-expenses-column-chart', imports: [StackedColumnChartComponent], template: `

Financial Overview

` }) export class IncomeExpensesColumnChart { transactionService = inject(TransactionService); currentTimeFrame = signal<'weekly' | 'monthly' | 'daily'>('monthly'); chartData = computed(() => [ { name: 'Income', data: [this.transactionService.totalIncome()] }, { name: 'Expenses', data: [this.transactionService.totalExpenses()] } ]); chartConfig: ChartConfig = { title: 'Income vs Expenses', categories: ['This Month'], height: 400, colors: ['#10B981', '#EF4444'], showToolbar: false, showLegend: true, horizontal: false }; setTimeFrame(timeFrame: 'weekly' | 'monthly' | 'daily') { this.currentTimeFrame.set(timeFrame); // Future: implement data filtering based on timeframe } } ``` -------------------------------- ### Categorization Utility Function Source: https://context7.com/zazagdev/budgie/llms.txt This JavaScript code provides a utility function to get a random note based on a category. It defines sample categories like 'Coffee' and 'Fuel' with associated notes. If a category is not found, it defaults to returning 'Transaction'. ```javascript function getCategoryNote(categoryName) { const notes = { 'Coffee': [ 'Morning coffee before work', 'Afternoon coffee break', 'Study session at coffee shop', ], 'Fuel': [ 'Weekly gas fill-up', 'Road trip fuel', 'Commute fuel cost', ], }; const categoryNotes = notes[categoryName] || ['Transaction']; return categoryNotes[Math.floor(Math.random() * categoryNotes.length)]; } ``` -------------------------------- ### Get Flattened Categories (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt Retrieves all categories and flattens them into a single-level array. This is useful for dropdowns or select components where hierarchical nesting is not required for display. It simulates latency and uses local storage. ```typescript import { Injectable } from '@angular/core'; import { Category } from '../models/category.model'; @Injectable({ providedIn: 'root' }) export class CategoriesService { async getFlatCategories(): Promise { await this.delay(Math.random() * 500); const categories = JSON.parse(localStorage.getItem('categories') || '[]'); const flatCategories: Category[] = []; const flattenCategories = (categories: Category[]) => { for (const category of categories) { flatCategories.push(category); if (category?.children) { flattenCategories(category.children); } } }; flattenCategories(categories); return flatCategories; } // ... other methods private delay(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } } ``` -------------------------------- ### Angular Application Bootstrap and Configuration Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code outlines the main application bootstrap process and configuration for an Angular 20 project. It includes settings for zoneless change detection and routing. The application is configured to use an AppConfig object that provides necessary services. ```typescript // Main bootstrap (src/main.ts) import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { App } from './app/app'; bootstrapApplication(App, appConfig) .catch((err) => console.error(err)); // Application config (src/app/app.config.ts) import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { provideZonelessChangeDetection, provideBrowserGlobalErrorListeners } from '@angular/core'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideBrowserGlobalErrorListeners(), provideZonelessChangeDetection(), // Angular 20 optimization provideRouter(routes), ], }; ``` -------------------------------- ### Set Initial Categories (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt Initializes local storage with default categories if none exist. This ensures that the application always has category data available upon first load. It includes a simulated delay. ```typescript import { Injectable } from '@angular/core'; import { defaultCategories } from '../data/categories'; @Injectable({ providedIn: 'root' }) export class CategoriesService { async setInitialCategories(): Promise { await this.delay(Math.random() * 500); if (!localStorage.getItem('categories')) { localStorage.setItem('categories', JSON.stringify(defaultCategories.categories)); } } // ... other methods private delay(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } } ``` -------------------------------- ### Angular Routing Configuration Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code defines the routes for an Angular application. It sets up a default route redirecting to '/home', a '/home' route that renders the HomeComponent, and a wildcard route that also redirects to '/home'. ```typescript import { Routes } from '@angular/router'; import { HomeComponent } from './components/home/home.component'; export const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: '**', redirectTo: '/home' }, ]; ``` -------------------------------- ### Generate Realistic Dummy Transactions in TypeScript Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code defines a service method for generating realistic dummy financial transactions. It simulates income and expenses with varying categories, amounts, and dates over a two-month period. Dependencies include a `generateUID` function and the `Transaction` type definition. The output is an array of sorted transaction objects, stored locally. ```typescript export class TransactionService { async generateDummyData(): Promise { await this.delay(Math.random() * 250); const dummyTransactions = this.createRealisticDummyData(); const currentTransactions = this._transactions(); const updatedTransactions = [...currentTransactions, ...dummyTransactions]; this._transactions.set(updatedTransactions); localStorage.setItem('transactions', JSON.stringify(updatedTransactions)); } private createRealisticDummyData(): Transaction[] { const transactions: Transaction[] = []; const now = new Date(); const expenseCategories = [ { id: '1.1.1', name: 'Fine Dining', minAmount: 45, maxAmount: 150 }, { id: '1.1.2', name: 'Casual Dining', minAmount: 15, maxAmount: 45 }, { id: '1.2.1', name: 'Groceries', minAmount: 25, maxAmount: 120 }, { id: '1.3.1', name: 'Coffee Shops', minAmount: 4, maxAmount: 12 }, { id: '2.1.1', name: 'Fuel', minAmount: 30, maxAmount: 80 }, ]; const incomeCategories = [ { id: '3.1.1', name: 'Salary', minAmount: 2500, maxAmount: 4500 }, { id: '3.2.1', name: 'Freelance', minAmount: 200, maxAmount: 800 }, ]; // Generate transactions for 2 months for (let monthOffset = 0; monthOffset < 2; monthOffset++) { const monthDate = new Date(now.getFullYear(), now.getMonth() - monthOffset, 1); const daysInMonth = new Date( monthDate.getFullYear(), monthDate.getMonth() + 1, 0 ).getDate(); // Add 1-2 monthly salary payments const salariesCount = Math.random() > 0.5 ? 2 : 1; for (let i = 0; i < salariesCount; i++) { const salaryDay = i === 0 ? Math.floor(Math.random() * 15) + 1 : Math.floor(Math.random() * 15) + 16; transactions.push({ id: generateUID(), type: 'income', date: new Date(monthDate.getFullYear(), monthDate.getMonth(), salaryDay), amount: Math.floor( Math.random() * (incomeCategories[0].maxAmount - incomeCategories[0].minAmount) + incomeCategories[0].minAmount ), note: 'Monthly salary payment', category: { id: '3.1.1', name: 'Salary' }, }); } // Add occasional freelance income (60% probability) if (Math.random() > 0.6) { const freelanceDay = Math.floor(Math.random() * daysInMonth) + 1; transactions.push({ id: generateUID(), type: 'income', date: new Date(monthDate.getFullYear(), monthDate.getMonth(), freelanceDay), amount: Math.floor(Math.random() * 600 + 200), note: 'Freelance project payment', category: { id: '3.2.1', name: 'Freelance' }, }); } // Generate daily expenses for (let day = 1; day <= daysInMonth; day++) { const currentDate = new Date(monthDate.getFullYear(), monthDate.getMonth(), day); const dayOfWeek = currentDate.getDay(); // More transactions on weekends (0-4) vs weekdays (0-3) const transactionsPerDay = dayOfWeek === 0 || dayOfWeek === 6 ? Math.floor(Math.random() * 4) : Math.floor(Math.random() * 3); for (let t = 0; t < transactionsPerDay; t++) { if (Math.random() > 0.3) { // 70% chance const category = expenseCategories[ Math.floor(Math.random() * expenseCategories.length) ]; const amount = Math.floor( Math.random() * (category.maxAmount - category.minAmount) + category.minAmount ); const finalAmount = Math.round(amount * (0.8 + Math.random() * 0.4) * 100) / 100; transactions.push({ id: generateUID(), type: 'expense', date: new Date(currentDate.getTime() + Math.random() * 24 * 60 * 60 * 1000), amount: finalAmount, note: this.getRealisticNote(category.name, finalAmount), category: { id: category.id, name: category.name }, }); } } } } return transactions.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime() ); } private getRealisticNote(categoryName: string, amount: number): string { const notes: { [key: string]: string[] } = { 'Fine Dining': [ 'Anniversary dinner at downtown restaurant', 'Business dinner with clients', 'Date night at Italian restaurant', ], 'Casual Dining': [ 'Lunch with friends', 'Quick dinner after work', 'Weekend brunch', ], 'Groceries': [ 'Weekly grocery shopping', 'Fresh produce and essentials', 'Monthly bulk shopping', ], 'Coffee Shops': [ ``` -------------------------------- ### Angular Root Component Template Structure Source: https://context7.com/zazagdev/budgie/llms.txt This HTML code represents the main template for the root Angular component. It sets up a flex layout with a sidebar and a main content area that utilizes the router-outlet for dynamic content loading. ```html
``` -------------------------------- ### Retrieve All Categories (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt Fetches all categories, returning them in a hierarchical structure. This function simulates network latency and relies on data stored in local storage. It's used to display category trees. ```typescript import { Injectable } from '@angular/core'; import { defaultCategories } from '../data/categories'; import { Category } from '../models/category.model'; @Injectable({ providedIn: 'root' }) export class CategoriesService { async getAllCategories(): Promise { await this.delay(Math.random() * 500); return JSON.parse(localStorage.getItem('categories') || '[]'); } // ... other methods private delay(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } } ``` -------------------------------- ### LocalStorage Data Persistence (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt This class abstracts data persistence to the browser's LocalStorage. It includes methods for saving, loading, and clearing transactions and categories, utilizing JSON stringification and parsing. It assumes data structures like `Transaction[]` and `Category[]`. The main limitation is the browser's LocalStorage size quota (typically 5-10MB per origin). ```typescript class StorageLayer { // Save transactions static saveTransactions(transactions: Transaction[]): void { localStorage.setItem('transactions', JSON.stringify(transactions)); } // Load transactions static loadTransactions(): Transaction[] { const data = localStorage.getItem('transactions'); return data ? JSON.parse(data) : []; } // Clear transactions static clearTransactions(): void { localStorage.removeItem('transactions'); } // Save categories static saveCategories(categories: Category[]): void { localStorage.setItem('categories', JSON.stringify(categories)); } // Load categories static loadCategories(): Category[] { const data = localStorage.getItem('categories'); return data ? JSON.parse(data) : []; } // Check if categories exist static hasCategories(): boolean { return localStorage.getItem('categories') !== null; } } ``` -------------------------------- ### Implement Transaction Service Add Method Source: https://context7.com/zazagdev/budgie/llms.txt The `TransactionService.add` method in TypeScript handles the creation and persistence of new transactions. It automatically generates unique IDs and timestamps, then updates the local storage. Dependencies include `Injectable` from Angular, `signal` for reactive state management, and a `generateUID` utility function. ```typescript // Service implementation (src/app/services/transaction.service.ts) import { Injectable, signal } from '@angular/core'; import { Transaction, TransactionRaw } from '../models/transaction.model'; import { generateUID } from '../utils/uid.util'; @Injectable({ providedIn: 'root' }) export class TransactionService { private _transactions = signal([]); public readonly transactions = this._transactions.asReadonly(); async add(transaction: TransactionRaw): Promise { await this.delay(Math.random() * 250); const transactionWithId: Transaction = { ...transaction, date: new Date(), id: generateUID(), // Generates: "1730203845678-a3d9f2" }; const currentTransactions = this._transactions(); const updatedTransactions = [...currentTransactions, transactionWithId]; this._transactions.set(updatedTransactions); localStorage.setItem('transactions', JSON.stringify(updatedTransactions)); return transactionWithId; } private delay(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } } ``` -------------------------------- ### Angular Root Component and Template Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code defines the root component of the Angular application, named 'App'. It imports necessary modules like RouterOutlet and SidebarComponent. The component's template is defined in './app.html' and its styles in './app.scss'. ```typescript import { Component, signal } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { SidebarComponent } from './components/shared/sidebar/sidebar'; @Component({ selector: 'app-root', imports: [RouterOutlet, SidebarComponent], templateUrl: './app.html', styleUrl: './app.scss', }) export class App { title = signal('Budgie'); } ``` -------------------------------- ### Angular Stacked Column Chart Component (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code defines a reusable Angular component for creating stacked column charts using ng-apexcharts. It accepts data and configuration inputs to render financial visualizations, handling chart updates via the OnChanges lifecycle hook. Dependencies include Angular core modules and ng-apexcharts. ```typescript // Component implementation (src/app/components/charts/raw/stacked-column-chart/) import { Component, Input, ViewChild, OnChanges } from '@angular/core'; import { ChartComponent, NgApexchartsModule } from 'ng-apexcharts'; import { ApexOptions } from 'apexcharts'; export interface ChartData { name: string; data: number[]; } export interface ChartConfig { title?: string; height?: number; categories: string[]; colors?: string[]; horizontal?: boolean; showToolbar?: boolean; showLegend?: boolean; } @Component({ selector: 'app-stacked-column-chart', imports: [NgApexchartsModule], template: `
@if (config.title) {

{{ config.title }}

}
` }) export class StackedColumnChartComponent implements OnChanges { @Input() data: ChartData[] = []; @Input() config: ChartConfig = { categories: [], height: 350, horizontal: false, showToolbar: true, showLegend: true }; @ViewChild('chart') chart!: ChartComponent; chartOptions: Partial = {}; ngOnChanges() { this.updateChart(); } updateChart() { this.chartOptions = { series: this.data, chart: { type: this.config.horizontal ? 'bar' : 'bar', height: this.config.height || 350, stacked: true, toolbar: { show: this.config.showToolbar ?? true }, zoom: { enabled: true } }, plotOptions: { bar: { horizontal: this.config.horizontal ?? false } }, xaxis: { categories: this.config.categories }, colors: this.config.colors || ['#10B981', '#EF4444'], legend: { show: this.config.showLegend ?? true, position: 'right', offsetY: 40 }, dataLabels: { enabled: false }, responsive: [{ breakpoint: 480, options: { legend: { position: 'bottom' } } }] }; } } ``` -------------------------------- ### Angular Transaction Service: Reactive Data Management Source: https://context7.com/zazagdev/budgie/llms.txt The TransactionService utilizes Angular's signals for reactive transaction data. It computes total income, expenses, and net total, providing readonly access to transaction lists. Dependencies include Angular's `computed` and `signal` utilities. ```typescript import { computed, signal } from '@angular/core'; export class TransactionService { private _transactions = signal([]); public readonly transactions = this._transactions.asReadonly(); public readonly totalIncome = computed(() => this._transactions() .filter(t => t.type === 'income') .reduce((sum, t) => sum + t.amount, 0) ); public readonly totalExpenses = computed(() => this._transactions() .filter(t => t.type === 'expense') .reduce((sum, t) => sum + t.amount, 0) ); public readonly netTotal = computed(() => this.totalIncome() - this.totalExpenses() ); async getAll(): Promise { await this.delay(Math.random() * 250); const transactions = JSON.parse(localStorage.getItem('transactions') || '[]'); this._transactions.set(transactions); return transactions; } async initialize(): Promise { await this.getAll(); } } ``` -------------------------------- ### Generate and Clear Dummy Data in Angular Component Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code defines an Angular component responsible for generating dummy transaction data and clearing all existing data. It utilizes a TransactionService and provides user confirmation before executing destructive actions. The dummy data generation includes realistic distributions of payments and expenses. ```typescript import { Component, inject } from '@angular/core'; @Component({ selector: 'app-home', template: `
` }) export class HomeComponent { transactionService = inject(TransactionService); async generateDummyData() { if (confirm('Generate 2 months of sample transactions?')) { await this.transactionService.generateDummyData(); console.log('Dummy data generated successfully'); // Results in ~100-150 transactions: // - 2-4 salary payments // - 0-2 freelance payments // - 80-140 expense transactions across various categories // - Realistic date distribution // - Varied amounts within category ranges } } async clearAllData() { if (confirm('Delete all transactions? This cannot be undone.')) { await this.transactionService.clearAllData(); console.log('All data cleared'); } } } ``` -------------------------------- ### Category Model Definition (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt Defines the structure for a category object, including properties like ID, name, type, icon, color, level, parent ID, and children. This interface is used throughout the application to represent category data. ```typescript export interface Category { id: string; // Hierarchical ID: "1.1.1.1" name: string; // Display name: "Fine Dining" type: 'income' | 'expense'; icon: string; // Emoji: "🍽️" color: string; // Hex color: "#FF6B6B" level: number; // Depth: 1-5 parentId: string | null; children: Category[] | []; } ``` -------------------------------- ### Angular Transaction List Component: Displaying Financial Data Source: https://context7.com/zazagdev/budgie/llms.txt The TransactionListComponent displays a list of transactions using Angular's template syntax and reactive signals injected from the TransactionService. It includes features for formatting currency and dates, and a delete functionality. Dependencies include `DatePipe` and `CurrencyPipe` from `@angular/common`. ```typescript import { Component, inject } from '@angular/core'; import { DatePipe, CurrencyPipe } from '@angular/common'; @Component({ selector: 'app-transaction-list', imports: [DatePipe, CurrencyPipe], template: `

Transactions ({{ transactions().length }})

@if (transactions().length === 0) {

No transactions yet. Start by adding your first transaction!

} @else { @for (transaction of transactions(); track transaction.id) { }
Type Category Amount Note Date Actions
@if (transaction.type === 'income') { 💰 Income } @else { 💸 Expense } {{ transaction.category.name }} {{ transaction.type === 'income' ? '+' : '-' }} {{ transaction.amount | currency }} {{ transaction.note }} {{ transaction.date | date: 'medium' }}
Totals: -{{ totalExpenses() | currency }} +{{ totalIncome() | currency }} Net: {{ netTotal() | currency }}
}
` }) export class TransactionListComponent { transactionService = inject(TransactionService); transactions = this.transactionService.transactions; totalExpenses = this.transactionService.totalExpenses; totalIncome = this.transactionService.totalIncome; netTotal = this.transactionService.netTotal; async deleteTransaction(id: string) { if (confirm('Are you sure you want to delete this transaction?')) { try { await this.transactionService.deleteTransaction(id); console.log('Transaction deleted successfully'); } catch (error) { console.error('Error deleting transaction:', error); } } } } ``` -------------------------------- ### Generate Timestamp-Based UID (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt This snippet provides a function to generate a unique identifier by combining a millisecond-precision timestamp with a random string. It's designed for low collision probability, suitable for transaction IDs. Dependencies include the built-in `Date.now()` and `Math.random()` functions. The output is a string in the format 'timestamp-random'. ```typescript export function generateUID(): string { const timestamp = Date.now(); const random = Math.random().toString(36).substring(2, 8); return `${timestamp}-${random}`; } ``` -------------------------------- ### Define Transaction Data Models Source: https://context7.com/zazagdev/budgie/llms.txt TypeScript interfaces define the structure for transaction data. `Transaction` includes an ID and date, while `TransactionRaw` represents the data before it's processed by the service. These models ensure data consistency and type safety throughout the application. ```typescript // Data models (src/app/models/transaction.model.ts) export interface Transaction { id: string; type: 'income' | 'expense'; date: Date; amount: number; note: string; category: { id: string; name: string }; } export interface TransactionRaw { type: 'income' | 'expense'; amount: number; note: string; category: { id: string; name: string }; } ``` -------------------------------- ### Category Selector Component Usage (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt An Angular component that utilizes the `CategoriesService` to fetch and display categories. It populates a select dropdown with flattened categories and a category tree view using hierarchical data. It injects the service and calls its methods in `ngOnInit`. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { CategoriesService } from '../services/categories.service'; import { Category } from '../models/category.model'; @Component({ selector: 'app-category-selector', template: `

Category Hierarchy:

@for (rootCategory of hierarchicalCategories; track rootCategory.id) { }
` }) export class CategorySelectorComponent implements OnInit { categoriesService = inject(CategoriesService); flatCategories: Category[] = []; hierarchicalCategories: Category[] = []; selectedCategoryId: string = ''; async ngOnInit() { await this.categoriesService.setInitialCategories(); this.flatCategories = await this.categoriesService.getFlatCategories(); this.hierarchicalCategories = await this.categoriesService.getAllCategories(); } } ``` -------------------------------- ### Create Transaction Form Component Source: https://context7.com/zazagdev/budgie/llms.txt The `TransactionFormComponent` in TypeScript provides a user interface for inputting new transaction details using Angular's reactive forms. It validates input, including type, category, amount, date, and an optional note, before submitting the data to the `TransactionService`. It depends on Angular's `Component`, `inject`, `FormControl`, `FormGroup`, and `Validators`. ```typescript // Component usage example (src/app/components/transactions/transaction-form/) import { Component, inject } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-transaction-form', template: `
` }) export class TransactionFormComponent { transactionService = inject(TransactionService); categories: Category[] = []; transactionForm = new FormGroup({ transactionType: new FormControl<'expense' | 'income'>('expense', { nonNullable: true, validators: [Validators.required], }), transactionCategory: new FormControl('', { nonNullable: true, validators: [Validators.required], }), transactionAmount: new FormControl(0, { nonNullable: true, validators: [Validators.required, Validators.min(0.01)], }), transactionDate: new FormControl(new Date().toISOString().substring(0, 10), { nonNullable: true, validators: [Validators.required], }), transactionNote: new FormControl('', { nonNullable: true }), }); async onSubmit() { if (this.transactionForm.invalid) { this.transactionForm.markAllAsTouched(); return; } const formValue = this.transactionForm.getRawValue(); const selectedCategory = this.categories.find( cat => cat.id === formValue.transactionCategory ); if (!selectedCategory) { console.error('Selected category not found'); return; } const data: TransactionRaw = { type: formValue.transactionType, amount: formValue.transactionAmount, note: formValue.transactionNote, category: { id: formValue.transactionCategory, name: selectedCategory.name, }, }; try { const newTransaction = await this.transactionService.add(data); console.log('Transaction added:', newTransaction); // Result: { id: "1730203845678-a3d9f2", type: "expense", amount: 45.50, ... } } catch (error) { console.error('Error adding transaction:', error); } } } ``` -------------------------------- ### Default Category Data Structure in TypeScript Source: https://context7.com/zazagdev/budgie/llms.txt Defines the default five-level category hierarchy for the Budgie application. This structure is used to categorize expenses and income, with each category having an ID, name, type, icon, color, level, parentId, and children. The 'children' property allows for nested subcategories, forming a tree-like structure. ```typescript export const defaultCategories = { categories: [ { id: '1', name: 'Food & Dining', type: 'expense', icon: '🍽️', color: '#FF6B6B', level: 1, parentId: null, children: [ { id: '1.1', name: 'Restaurants', type: 'expense', icon: '🍴', color: '#FF8787', level: 2, parentId: '1', children: [ { id: '1.1.1', name: 'Fine Dining', type: 'expense', icon: '🍷', color: '#FFA3A3', level: 3, parentId: '1.1', children: [ { id: '1.1.1.1', name: 'Date Night', type: 'expense', icon: '❤️', color: '#FFBFBF', level: 4, parentId: '1.1.1', children: [ { id: '1.1.1.1.1', name: 'Anniversary', type: 'expense', icon: '💍', color: '#FFDBDB', level: 5, parentId: '1.1.1.1', children: [] }, { id: '1.1.1.1.2', name: 'Special Occasions', type: 'expense', icon: '🎉', color: '#FFE7E7', level: 5, parentId: '1.1.1.1', children: [] } ] } ] } ] }, { id: '1.2', name: 'Groceries', type: 'expense', icon: '🛒', color: '#FF8787', level: 2, parentId: '1', children: [...] } ] }, { id: '3', name: 'Income', type: 'income', icon: '💰', color: '#10B981', level: 1, parentId: null, children: [ { id: '3.1', name: 'Employment', type: 'income', icon: '💼', color: '#34D399', level: 2, parentId: '3', children: [ { id: '3.1.1', name: 'Salary', type: 'income', icon: '💵', color: '#6EE7B7', level: 3, parentId: '3.1', children: [] } ] } ] } ] }; ``` -------------------------------- ### Display Transactions List (Angular) Source: https://github.com/zazagdev/budgie/blob/master/src/app/components/transactions/transaction-list/transaction-list.html This snippet renders a list of financial transactions. It conditionally displays a 'No transactions yet' message if the transaction list is empty. Otherwise, it iterates through each transaction, displaying its type, category, amount, note, and date. It also calculates and displays total expenses, total income, and net total. ```html {{ transactions().length }} transactions @if (transactions().length === 0) { ### No transactions yet Start by adding your first transaction above. } @else { @for (transaction of transactions(); track transaction.id) { Type Category Amount Note Date Actions @if (transaction.type === 'income') { 💰 Income } @else { 💸 Expense } {{ transaction.category.name }} @if (transaction.type === 'income') { +${{ transaction.amount | number : '1.2-2' }} } @else { -${{ transaction.amount | number : '1.2-2' }} } {{ transaction.note || 'No note' }} {{ transaction.date | date : 'mediumDate' }} } Total Expenses: ${{ totalExpenses() | number : '1.2-2' }} Total Income: ${{ totalIncome() | number : '1.2-2' }} Net Total: ${{ netTotal() | number : '1.2-2' }} } ``` -------------------------------- ### Delete Transaction in Budgie (TypeScript) Source: https://context7.com/zazagdev/budgie/llms.txt This TypeScript code demonstrates how to delete a transaction in the Budgie application. The `TransactionService` method `deleteTransaction` removes the transaction from the internal state and localStorage, triggering UI recalculations via signals. The `TransactionListComponent` provides a button to initiate the deletion process, with a confirmation dialog. ```typescript // Service method (src/app/services/transaction.service.ts) export class TransactionService { async deleteTransaction(id: string): Promise { await this.delay(Math.random() * 250); const updatedTransactions = this._transactions().filter(t => t.id !== id); this._transactions.set(updatedTransactions); localStorage.setItem('transactions', JSON.stringify(updatedTransactions)); } } // Component implementation import { Component, inject } from '@angular/core'; @Component({ selector: 'app-transaction-list', template: ` @for (transaction of transactions(); track transaction.id) { {{ transaction.category.name }} {{ transaction.amount | currency }} } ` }) export class TransactionListComponent { transactionService = inject(TransactionService); transactions = this.transactionService.transactions; async deleteTransaction(id: string) { if (confirm('Delete this transaction?')) { await this.transactionService.deleteTransaction(id); // Signals automatically update: transactions(), totalIncome(), totalExpenses(), netTotal() // All bound components re-render without manual refresh } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.