Quality-of-life enhancements: CSV import/export, opening balances, interest rates, mobile UX

- CSV import/export for Units, Projects, and Vendors with match-on-name/number upsert
- Cash Flow report toggle for Cash Only vs Cash + Investments
- Per-account and bulk opening balance setting with as-of date
- Interest rate field on normal accounts with estimated monthly/annual interest display
- Mobile sidebar auto-close on navigation
- Shared CSV parsing/export utility extracted to frontend/src/utils/csv.ts

DB migration needed for existing tenants:
  ALTER TABLE accounts ADD COLUMN IF NOT EXISTS interest_rate DECIMAL(6,4);

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-25 09:13:51 -05:00
parent 32af961173
commit 45a267d787
21 changed files with 1015 additions and 128 deletions

View File

@@ -32,6 +32,23 @@ export class AccountsController {
return this.accountsService.setPrimary(id);
}
@Post('bulk-opening-balances')
@ApiOperation({ summary: 'Set opening balances for multiple accounts' })
bulkSetOpeningBalances(
@Body() dto: { asOfDate: string; entries: { accountId: string; targetBalance: number }[] },
) {
return this.accountsService.bulkSetOpeningBalances(dto);
}
@Post(':id/opening-balance')
@ApiOperation({ summary: 'Set opening balance for an account at a specific date' })
setOpeningBalance(
@Param('id') id: string,
@Body() dto: { targetBalance: number; asOfDate: string; memo?: string },
) {
return this.accountsService.setOpeningBalance(id, dto);
}
@Post(':id/adjust-balance')
@ApiOperation({ summary: 'Adjust account balance to a target amount' })
adjustBalance(

View File

@@ -55,8 +55,8 @@ export class AccountsService {
}
const insertResult = await this.tenant.query(
`INSERT INTO accounts (account_number, name, description, account_type, fund_type, parent_account_id, is_1099_reportable)
VALUES ($1, $2, $3, $4, $5, $6, $7)
`INSERT INTO accounts (account_number, name, description, account_type, fund_type, parent_account_id, is_1099_reportable, interest_rate)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id`,
[
dto.accountNumber,
@@ -66,6 +66,7 @@ export class AccountsService {
dto.fundType,
dto.parentAccountId || null,
dto.is1099Reportable || false,
dto.interestRate || null,
],
);
const accountId = Array.isArray(insertResult[0]) ? insertResult[0][0].id : insertResult[0].id;
@@ -172,6 +173,7 @@ export class AccountsService {
if (dto.is1099Reportable !== undefined) { sets.push(`is_1099_reportable = $${idx++}`); params.push(dto.is1099Reportable); }
if (dto.isActive !== undefined) { sets.push(`is_active = $${idx++}`); params.push(dto.isActive); }
if (dto.isPrimary !== undefined) { sets.push(`is_primary = $${idx++}`); params.push(dto.isPrimary); }
if (dto.interestRate !== undefined) { sets.push(`interest_rate = $${idx++}`); params.push(dto.interestRate); }
if (!sets.length) return account;
@@ -204,7 +206,30 @@ export class AccountsService {
return this.findOne(id);
}
async adjustBalance(id: string, dto: { targetBalance: number; asOfDate: string; memo?: string }) {
async setOpeningBalance(id: string, dto: { targetBalance: number; asOfDate: string; memo?: string }) {
return this.adjustBalance(id, dto, 'opening_balance');
}
async bulkSetOpeningBalances(dto: { asOfDate: string; entries: { accountId: string; targetBalance: number }[] }) {
let processed = 0, skipped = 0;
const errors: string[] = [];
for (const entry of dto.entries) {
try {
const result = await this.setOpeningBalance(entry.accountId, {
targetBalance: entry.targetBalance,
asOfDate: dto.asOfDate,
});
if (result.message === 'No adjustment needed') skipped++;
else processed++;
} catch (err: any) {
errors.push(`${entry.accountId}: ${err.message}`);
}
}
return { processed, skipped, errors };
}
async adjustBalance(id: string, dto: { targetBalance: number; asOfDate: string; memo?: string }, entryType = 'adjustment') {
const account = await this.findOne(id);
// Get current balance for this account using trial balance logic
@@ -282,16 +307,20 @@ export class AccountsService {
const equityDebit = targetCredit > 0 ? targetCredit : 0;
const equityCredit = targetDebit > 0 ? targetDebit : 0;
const memo = dto.memo || `Balance adjustment to ${dto.targetBalance}`;
const defaultMemo = entryType === 'opening_balance'
? `Opening balance for ${account.name}`
: `Balance adjustment to ${dto.targetBalance}`;
const memo = dto.memo || defaultMemo;
// Create journal entry
const jeRows = await this.tenant.query(
`INSERT INTO journal_entries (entry_date, description, entry_type, fiscal_period_id, is_posted, posted_at, created_by)
VALUES ($1, $2, 'adjustment', $3, true, NOW(), $4)
VALUES ($1, $2, $3, $4, true, NOW(), $5)
RETURNING *`,
[
dto.asOfDate,
memo,
entryType,
fiscalPeriodId,
'00000000-0000-0000-0000-000000000000',
],

View File

@@ -36,4 +36,8 @@ export class CreateAccountDto {
@ApiProperty({ required: false, default: 0 })
@IsOptional()
initialBalance?: number;
@ApiProperty({ required: false, description: 'Annual interest rate as a percentage' })
@IsOptional()
interestRate?: number;
}

View File

@@ -41,4 +41,8 @@ export class UpdateAccountDto {
@IsBoolean()
@IsOptional()
isPrimary?: boolean;
@ApiProperty({ required: false, description: 'Annual interest rate as a percentage' })
@IsOptional()
interestRate?: number;
}

View File

@@ -1,5 +1,6 @@
import { Controller, Get, Post, Put, Body, Param, UseGuards } from '@nestjs/common';
import { Controller, Get, Post, Put, Body, Param, Res, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { Response } from 'express';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { ProjectsService } from './projects.service';
@@ -13,12 +14,22 @@ export class ProjectsController {
@Get()
findAll() { return this.service.findAll(); }
@Get('export')
async exportCSV(@Res() res: Response) {
const csv = await this.service.exportCSV();
res.set({ 'Content-Type': 'text/csv', 'Content-Disposition': 'attachment; filename="projects.csv"' });
res.send(csv);
}
@Get('planning')
findForPlanning() { return this.service.findForPlanning(); }
@Get(':id')
findOne(@Param('id') id: string) { return this.service.findOne(id); }
@Post('import')
importCSV(@Body() rows: any[]) { return this.service.importCSV(rows); }
@Post()
create(@Body() dto: any) { return this.service.create(dto); }

View File

@@ -176,6 +176,87 @@ export class ProjectsService {
return rows[0];
}
async exportCSV(): Promise<string> {
const rows = await this.tenant.query(
`SELECT name, description, category, estimated_cost, actual_cost, fund_source,
useful_life_years, remaining_life_years, condition_rating,
last_replacement_date, next_replacement_date, planned_date,
target_year, target_month, status, priority, notes
FROM projects WHERE is_active = true ORDER BY name`,
);
const headers = ['*name', 'description', '*category', '*estimated_cost', 'actual_cost', 'fund_source',
'useful_life_years', 'remaining_life_years', 'condition_rating',
'last_replacement_date', 'next_replacement_date', 'planned_date',
'target_year', 'target_month', 'status', 'priority', 'notes'];
const keys = headers.map(h => h.replace(/^\*/, ''));
const lines = [headers.join(',')];
for (const r of rows) {
lines.push(keys.map((k) => {
let v = r[k] ?? '';
if (v instanceof Date) v = v.toISOString().split('T')[0];
const s = String(v);
return s.includes(',') || s.includes('"') || s.includes('\n') ? `"${s.replace(/"/g, '""')}"` : s;
}).join(','));
}
return lines.join('\n');
}
async importCSV(rows: any[]) {
let created = 0, updated = 0;
const errors: string[] = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const name = (row.name || '').trim();
if (!name) { errors.push(`Row ${i + 1}: missing name (required)`); continue; }
if (!row.category) { errors.push(`Row ${i + 1}: missing category (required)`); continue; }
if (!row.estimated_cost) { errors.push(`Row ${i + 1}: missing estimated_cost (required)`); continue; }
try {
const existing = await this.tenant.query('SELECT id FROM projects WHERE name = $1 AND is_active = true', [name]);
if (existing.length) {
const sets: string[] = [];
const params: any[] = [existing[0].id];
let idx = 2;
const fields = ['description', 'category', 'estimated_cost', 'actual_cost', 'fund_source',
'useful_life_years', 'remaining_life_years', 'condition_rating',
'last_replacement_date', 'next_replacement_date', 'planned_date',
'target_year', 'target_month', 'status', 'priority', 'notes'];
for (const f of fields) {
if (row[f] !== undefined && row[f] !== '') {
sets.push(`${f} = $${idx++}`);
params.push(row[f]);
}
}
if (sets.length) {
sets.push('updated_at = NOW()');
await this.tenant.query(`UPDATE projects SET ${sets.join(', ')} WHERE id = $1`, params);
}
updated++;
} else {
await this.tenant.query(
`INSERT INTO projects (name, description, category, estimated_cost, actual_cost, fund_source,
useful_life_years, remaining_life_years, condition_rating,
last_replacement_date, next_replacement_date, planned_date,
target_year, target_month, status, priority, notes)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17)`,
[name, row.description || null, row.category, parseFloat(row.estimated_cost) || 0,
row.actual_cost || null, row.fund_source || 'reserve',
row.useful_life_years || null, row.remaining_life_years || null,
row.condition_rating || null, row.last_replacement_date || null,
row.next_replacement_date || null, row.planned_date || null,
row.target_year || null, row.target_month || null,
row.status || 'planned', row.priority || 3, row.notes || null],
);
created++;
}
} catch (err: any) {
errors.push(`Row ${i + 1} (${name}): ${err.message}`);
}
}
return { imported: created + updated, created, updated, errors };
}
async updatePlannedDate(id: string, planned_date: string) {
await this.findOne(id);
const rows = await this.tenant.query(

View File

@@ -29,11 +29,17 @@ export class ReportsController {
}
@Get('cash-flow')
getCashFlowStatement(@Query('from') from?: string, @Query('to') to?: string) {
getCashFlowStatement(
@Query('from') from?: string,
@Query('to') to?: string,
@Query('includeInvestments') includeInvestments?: string,
) {
const now = new Date();
const defaultFrom = `${now.getFullYear()}-01-01`;
const defaultTo = now.toISOString().split('T')[0];
return this.reportsService.getCashFlowStatement(from || defaultFrom, to || defaultTo);
return this.reportsService.getCashFlowStatement(
from || defaultFrom, to || defaultTo, includeInvestments === 'true',
);
}
@Get('aging')

View File

@@ -178,7 +178,7 @@ export class ReportsService {
return { nodes, links, total_income: totalIncome, total_expenses: totalExpenses, net_cash_flow: netFlow };
}
async getCashFlowStatement(from: string, to: string) {
async getCashFlowStatement(from: string, to: string, includeInvestments = false) {
// Operating activities: income minus expenses from journal entries
const operating = await this.tenant.query(`
SELECT a.name, a.account_type,
@@ -222,6 +222,11 @@ export class ReportsService {
ORDER BY a.name
`, [from, to]);
// Asset filter: cash-only vs cash + investment accounts
const assetFilter = includeInvestments
? `a.account_type = 'asset'`
: `a.account_type = 'asset' AND a.name LIKE '%Cash%'`;
// Cash beginning and ending balances
const beginCash = await this.tenant.query(`
SELECT COALESCE(SUM(sub.bal), 0) as balance FROM (
@@ -231,7 +236,7 @@ export class ReportsService {
LEFT JOIN journal_entries je ON je.id = jel.journal_entry_id
AND je.is_posted = true AND je.is_void = false
AND je.entry_date < $1
WHERE a.account_type = 'asset' AND a.name LIKE '%Cash%' AND a.is_active = true
WHERE ${assetFilter} AND a.is_active = true
GROUP BY a.id
) sub
`, [from]);
@@ -244,11 +249,20 @@ export class ReportsService {
LEFT JOIN journal_entries je ON je.id = jel.journal_entry_id
AND je.is_posted = true AND je.is_void = false
AND je.entry_date <= $1
WHERE a.account_type = 'asset' AND a.name LIKE '%Cash%' AND a.is_active = true
WHERE ${assetFilter} AND a.is_active = true
GROUP BY a.id
) sub
`, [to]);
// Include investment_accounts table balances when requested
let investmentBalance = 0;
if (includeInvestments) {
const inv = await this.tenant.query(
`SELECT COALESCE(SUM(current_value), 0) as total FROM investment_accounts WHERE is_active = true`,
);
investmentBalance = parseFloat(inv[0]?.total || '0');
}
const operatingItems = operating.map((r: any) => ({
name: r.name, type: r.account_type, amount: parseFloat(r.amount),
}));
@@ -258,11 +272,12 @@ export class ReportsService {
const totalOperating = operatingItems.reduce((s: number, r: any) => s + r.amount, 0);
const totalReserve = reserveItems.reduce((s: number, r: any) => s + r.amount, 0);
const beginningBalance = parseFloat(beginCash[0]?.balance || '0');
const endingBalance = parseFloat(endCash[0]?.balance || '0');
const beginningBalance = parseFloat(beginCash[0]?.balance || '0') + (includeInvestments ? investmentBalance : 0);
const endingBalance = parseFloat(endCash[0]?.balance || '0') + investmentBalance;
return {
from, to,
include_investments: includeInvestments,
operating_activities: operatingItems,
reserve_activities: reserveItems,
total_operating: totalOperating.toFixed(2),
@@ -270,6 +285,7 @@ export class ReportsService {
net_cash_change: (totalOperating + totalReserve).toFixed(2),
beginning_cash: beginningBalance.toFixed(2),
ending_cash: endingBalance.toFixed(2),
investment_balance: investmentBalance.toFixed(2),
};
}

View File

@@ -1,5 +1,6 @@
import { Controller, Get, Post, Put, Delete, Body, Param, UseGuards } from '@nestjs/common';
import { Controller, Get, Post, Put, Delete, Body, Param, Res, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { Response } from 'express';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { UnitsService } from './units.service';
@@ -13,9 +14,19 @@ export class UnitsController {
@Get()
findAll() { return this.unitsService.findAll(); }
@Get('export')
async exportCSV(@Res() res: Response) {
const csv = await this.unitsService.exportCSV();
res.set({ 'Content-Type': 'text/csv', 'Content-Disposition': 'attachment; filename="units.csv"' });
res.send(csv);
}
@Get(':id')
findOne(@Param('id') id: string) { return this.unitsService.findOne(id); }
@Post('import')
importCSV(@Body() rows: any[]) { return this.unitsService.importCSV(rows); }
@Post()
create(@Body() dto: any) { return this.unitsService.create(dto); }

View File

@@ -73,6 +73,90 @@ export class UnitsService {
return rows[0];
}
async exportCSV(): Promise<string> {
const rows = await this.tenant.query(
`SELECT unit_number, address_line1, city, state, zip_code, square_footage, lot_size,
owner_name, owner_email, owner_phone, is_rented, monthly_assessment, status
FROM units WHERE status != 'inactive' ORDER BY unit_number`,
);
const headers = ['unit_number', 'address_line1', 'city', 'state', 'zip_code', 'square_footage', 'lot_size',
'owner_name', 'owner_email', 'owner_phone', 'is_rented', 'monthly_assessment', 'status'];
const lines = [headers.join(',')];
for (const r of rows) {
lines.push(headers.map((h) => {
const v = r[h] ?? '';
const s = String(v);
return s.includes(',') || s.includes('"') ? `"${s.replace(/"/g, '""')}"` : s;
}).join(','));
}
return lines.join('\n');
}
async importCSV(rows: any[]) {
let created = 0, updated = 0;
const errors: string[] = [];
// Resolve default assessment group for new units
let defaultGroupId: string | null = null;
const defaultGroup = await this.tenant.query(
'SELECT id FROM assessment_groups WHERE is_default = true AND is_active = true LIMIT 1',
);
if (defaultGroup.length) defaultGroupId = defaultGroup[0].id;
else {
const anyGroup = await this.tenant.query('SELECT id FROM assessment_groups WHERE is_active = true LIMIT 1');
if (anyGroup.length) defaultGroupId = anyGroup[0].id;
}
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const unitNumber = (row.unit_number || '').trim();
if (!unitNumber) { errors.push(`Row ${i + 1}: missing unit_number`); continue; }
try {
const existing = await this.tenant.query('SELECT id FROM units WHERE unit_number = $1', [unitNumber]);
if (existing.length) {
await this.tenant.query(
`UPDATE units SET
address_line1 = COALESCE(NULLIF($2, ''), address_line1),
city = COALESCE(NULLIF($3, ''), city),
state = COALESCE(NULLIF($4, ''), state),
zip_code = COALESCE(NULLIF($5, ''), zip_code),
square_footage = COALESCE(NULLIF($6, '')::integer, square_footage),
lot_size = COALESCE(NULLIF($7, '')::decimal, lot_size),
owner_name = COALESCE(NULLIF($8, ''), owner_name),
owner_email = COALESCE(NULLIF($9, ''), owner_email),
owner_phone = COALESCE(NULLIF($10, ''), owner_phone),
is_rented = COALESCE(NULLIF($11, '')::boolean, is_rented),
monthly_assessment = COALESCE(NULLIF($12, '')::decimal, monthly_assessment),
status = COALESCE(NULLIF($13, ''), status),
updated_at = NOW()
WHERE id = $1`,
[existing[0].id, row.address_line1, row.city, row.state, row.zip_code,
row.square_footage, row.lot_size, row.owner_name, row.owner_email,
row.owner_phone, row.is_rented, row.monthly_assessment, row.status],
);
updated++;
} else {
if (!defaultGroupId) { errors.push(`Row ${i + 1}: no assessment group available for new unit`); continue; }
await this.tenant.query(
`INSERT INTO units (unit_number, address_line1, city, state, zip_code, square_footage, lot_size,
owner_name, owner_email, owner_phone, is_rented, monthly_assessment, status, assessment_group_id)
VALUES ($1, $2, $3, $4, $5, NULLIF($6, '')::integer, NULLIF($7, '')::decimal,
$8, $9, $10, COALESCE(NULLIF($11, '')::boolean, false), COALESCE(NULLIF($12, '')::decimal, 0), COALESCE(NULLIF($13, ''), 'active'), $14)`,
[unitNumber, row.address_line1 || null, row.city || null, row.state || null, row.zip_code || null,
row.square_footage || '', row.lot_size || '', row.owner_name || null, row.owner_email || null,
row.owner_phone || null, row.is_rented || '', row.monthly_assessment || '', row.status || '', defaultGroupId],
);
created++;
}
} catch (err: any) {
errors.push(`Row ${i + 1} (${unitNumber}): ${err.message}`);
}
}
return { imported: created + updated, created, updated, errors };
}
async delete(id: string) {
await this.findOne(id);

View File

@@ -1,5 +1,6 @@
import { Controller, Get, Post, Put, Body, Param, Query, UseGuards } from '@nestjs/common';
import { Controller, Get, Post, Put, Body, Param, Query, Res, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { Response } from 'express';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { VendorsService } from './vendors.service';
@@ -13,6 +14,13 @@ export class VendorsController {
@Get()
findAll() { return this.vendorsService.findAll(); }
@Get('export')
async exportCSV(@Res() res: Response) {
const csv = await this.vendorsService.exportCSV();
res.set({ 'Content-Type': 'text/csv', 'Content-Disposition': 'attachment; filename="vendors.csv"' });
res.send(csv);
}
@Get('1099-data')
get1099Data(@Query('year') year: string) {
return this.vendorsService.get1099Data(parseInt(year) || new Date().getFullYear());
@@ -21,6 +29,9 @@ export class VendorsController {
@Get(':id')
findOne(@Param('id') id: string) { return this.vendorsService.findOne(id); }
@Post('import')
importCSV(@Body() rows: any[]) { return this.vendorsService.importCSV(rows); }
@Post()
create(@Body() dto: any) { return this.vendorsService.create(dto); }

View File

@@ -40,6 +40,70 @@ export class VendorsService {
return rows[0];
}
async exportCSV(): Promise<string> {
const rows = await this.tenant.query(
`SELECT name, contact_name, email, phone, address_line1, city, state, zip_code, tax_id, is_1099_eligible
FROM vendors WHERE is_active = true ORDER BY name`,
);
const headers = ['name', 'contact_name', 'email', 'phone', 'address_line1', 'city', 'state', 'zip_code', 'tax_id', 'is_1099_eligible'];
const lines = [headers.join(',')];
for (const r of rows) {
lines.push(headers.map((h) => {
const v = r[h] ?? '';
const s = String(v);
return s.includes(',') || s.includes('"') ? `"${s.replace(/"/g, '""')}"` : s;
}).join(','));
}
return lines.join('\n');
}
async importCSV(rows: any[]) {
let created = 0, updated = 0;
const errors: string[] = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const name = (row.name || '').trim();
if (!name) { errors.push(`Row ${i + 1}: missing name (required)`); continue; }
try {
const existing = await this.tenant.query('SELECT id FROM vendors WHERE name = $1 AND is_active = true', [name]);
if (existing.length) {
await this.tenant.query(
`UPDATE vendors SET
contact_name = COALESCE(NULLIF($2, ''), contact_name),
email = COALESCE(NULLIF($3, ''), email),
phone = COALESCE(NULLIF($4, ''), phone),
address_line1 = COALESCE(NULLIF($5, ''), address_line1),
city = COALESCE(NULLIF($6, ''), city),
state = COALESCE(NULLIF($7, ''), state),
zip_code = COALESCE(NULLIF($8, ''), zip_code),
tax_id = COALESCE(NULLIF($9, ''), tax_id),
is_1099_eligible = COALESCE(NULLIF($10, '')::boolean, is_1099_eligible),
updated_at = NOW()
WHERE id = $1`,
[existing[0].id, row.contact_name, row.email, row.phone, row.address_line1,
row.city, row.state, row.zip_code, row.tax_id, row.is_1099_eligible],
);
updated++;
} else {
await this.tenant.query(
`INSERT INTO vendors (name, contact_name, email, phone, address_line1, city, state, zip_code, tax_id, is_1099_eligible)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[name, row.contact_name || null, row.email || null, row.phone || null,
row.address_line1 || null, row.city || null, row.state || null,
row.zip_code || null, row.tax_id || null,
row.is_1099_eligible === 'true' || row.is_1099_eligible === true || false],
);
created++;
}
} catch (err: any) {
errors.push(`Row ${i + 1} (${name}): ${err.message}`);
}
}
return { imported: created + updated, created, updated, errors };
}
async get1099Data(year: number) {
return this.tenant.query(`
SELECT v.*, COALESCE(SUM(p_amounts.amount), 0) as total_paid