Implement full balance sheet features using libdrcr
This commit is contained in:
parent
25697b501c
commit
a967c87dab
@ -33,7 +33,11 @@ use tokio::task::spawn_blocking;
|
||||
use crate::AppState;
|
||||
|
||||
#[tauri::command]
|
||||
pub(crate) async fn get_balance_sheet(state: State<'_, Mutex<AppState>>) -> Result<String, ()> {
|
||||
pub(crate) async fn get_balance_sheet(
|
||||
state: State<'_, Mutex<AppState>>,
|
||||
eofy_date: String,
|
||||
dates: Vec<String>,
|
||||
) -> Result<String, ()> {
|
||||
let state = state.lock().await;
|
||||
let db_filename = state.db_filename.clone().unwrap();
|
||||
|
||||
@ -45,14 +49,19 @@ pub(crate) async fn get_balance_sheet(state: State<'_, Mutex<AppState>>) -> Resu
|
||||
// Initialise ReportingContext
|
||||
let mut context = ReportingContext::new(
|
||||
db_connection,
|
||||
NaiveDate::from_ymd_opt(2025, 6, 30).unwrap(),
|
||||
NaiveDate::parse_from_str(eofy_date.as_str(), "%Y-%m-%d").unwrap(),
|
||||
"$".to_string(),
|
||||
);
|
||||
register_lookup_fns(&mut context);
|
||||
register_dynamic_builders(&mut context);
|
||||
|
||||
// Get balance sheet
|
||||
|
||||
let mut date_args = Vec::new();
|
||||
for date in dates.iter() {
|
||||
date_args.push(DateArgs {
|
||||
date: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap(),
|
||||
})
|
||||
}
|
||||
let targets = vec![
|
||||
ReportingProductId {
|
||||
name: "CalculateIncomeTax",
|
||||
@ -63,23 +72,18 @@ pub(crate) async fn get_balance_sheet(state: State<'_, Mutex<AppState>>) -> Resu
|
||||
name: "BalanceSheet",
|
||||
kind: ReportingProductKind::Generic,
|
||||
args: Box::new(MultipleDateArgs {
|
||||
dates: vec![DateArgs {
|
||||
date: NaiveDate::from_ymd_opt(2025, 6, 30).unwrap(),
|
||||
}],
|
||||
dates: date_args.clone(),
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
// Run report
|
||||
let products = generate_report(targets, &context).unwrap();
|
||||
let result = products
|
||||
.get_or_err(&ReportingProductId {
|
||||
name: "BalanceSheet",
|
||||
kind: ReportingProductKind::Generic,
|
||||
args: Box::new(MultipleDateArgs {
|
||||
dates: vec![DateArgs {
|
||||
date: NaiveDate::from_ymd_opt(2025, 6, 30).unwrap(),
|
||||
}],
|
||||
}),
|
||||
args: Box::new(MultipleDateArgs { dates: date_args }),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
|
@ -1,63 +0,0 @@
|
||||
<!--
|
||||
DrCr: Web-based double-entry bookkeeping framework
|
||||
Copyright (C) 2022–2025 Lee Yingtong Li (RunasSudo)
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
-->
|
||||
|
||||
<template>
|
||||
<template v-if="reports.length > 0">
|
||||
<h1 class="page-heading">
|
||||
{{ reports[0].title }}
|
||||
</h1>
|
||||
|
||||
<slot />
|
||||
|
||||
<table class="min-w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-300">
|
||||
<th></th>
|
||||
<th v-for="label of labels" class="py-0.5 pl-1 text-gray-900 font-semibold text-end">{{ label }} </th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<ComparativeDynamicReportEntry :row="[row[0], row]" v-for="row of joinedEntries" />
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, defineProps } from 'vue';
|
||||
|
||||
import { DynamicReport } from '../reports/base.ts';
|
||||
import ComparativeDynamicReportEntry from './ComparativeDynamicReportEntry.vue';
|
||||
|
||||
const { reports, labels } = defineProps<{ reports: DynamicReport[], labels: string[] }>();
|
||||
|
||||
const joinedEntries = computed(() => {
|
||||
// FIXME: Validate reports are of the same type, etc.
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < reports[0].entries.length; i++) {
|
||||
const thisRow = [];
|
||||
for (let report of reports) {
|
||||
thisRow.push(report.entries[i]);
|
||||
}
|
||||
result.push(thisRow);
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
</script>
|
@ -1,106 +0,0 @@
|
||||
<!--
|
||||
DrCr: Web-based double-entry bookkeeping framework
|
||||
Copyright (C) 2022–2025 Lee Yingtong Li (RunasSudo)
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
-->
|
||||
|
||||
<template>
|
||||
<template v-if="row[0] instanceof Entry">
|
||||
<!-- NB: Subtotal and Calculated are subclasses of Entry -->
|
||||
<tr :class="row[0].bordered ? 'border-y border-gray-300' : null">
|
||||
<component :is="row[0].heading ? 'th' : 'td'" class="py-0.5 pr-1 text-gray-900 text-start" :class="{ 'font-semibold': row[0].heading }">
|
||||
<a :href="row[0].link" class="hover:text-blue-700 hover:underline" v-if="row[0].link !== null">{{ row[0].text }}</a>
|
||||
<template v-if="row[0].link === null">{{ row[0].text }}</template>
|
||||
</component>
|
||||
<template v-for="entry of row[1]">
|
||||
<component :is="row[0].heading ? 'th' : 'td'" class="py-0.5 pl-1 text-gray-900 text-end" :class="{ 'font-semibold': row[0].heading }" v-html="entry ? ppBracketed((entry as Entry).quantity, (entry as Entry).link ?? undefined) : ''" />
|
||||
</template>
|
||||
</tr>
|
||||
</template>
|
||||
<template v-if="row[0] instanceof Section">
|
||||
<tr v-if="row[0].title !== null">
|
||||
<th class="py-0.5 pr-1 text-gray-900 font-semibold text-start">{{ row[0].title }}</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
<ComparativeDynamicReportEntry :row="childRow" v-for="childRow of joinedChildren" />
|
||||
</template>
|
||||
<template v-if="row[0] instanceof Spacer">
|
||||
<tr><td :colspan="row[1].length + 1" class="py-0.5"> </td></tr>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, defineProps } from 'vue';
|
||||
|
||||
import { ppBracketed } from '../display.ts';
|
||||
import { DynamicReportNode, Entry, Section, Spacer, Subtotal } from '../reports/base.ts';
|
||||
|
||||
const { row } = defineProps<{ row: [DynamicReportNode, (DynamicReportNode | null)[]] }>();
|
||||
|
||||
const joinedChildren = computed(() => {
|
||||
// First get all children's names
|
||||
const joinedNames: string[] = [];
|
||||
for (let cell of row[1]) {
|
||||
for (let entry of (cell as any).entries) {
|
||||
if (entry instanceof Subtotal) { // Handle Subtotal separately
|
||||
continue;
|
||||
}
|
||||
if (!joinedNames.includes((entry as any).text)) {
|
||||
joinedNames.push((entry as any).text);
|
||||
}
|
||||
}
|
||||
}
|
||||
joinedNames.sort();
|
||||
|
||||
// Then return joined children in order of sorted names
|
||||
const result: [DynamicReportNode, (DynamicReportNode | null)[]][] = [];
|
||||
for (let name of joinedNames) {
|
||||
const thisRow: DynamicReportNode[] = [];
|
||||
let thisRowExample = null;
|
||||
for (let cell of row[1]) {
|
||||
let thisCell = null;
|
||||
for (let entry of (cell as any).entries) {
|
||||
if ((entry as any).text === name) {
|
||||
thisCell = entry;
|
||||
thisRowExample = entry;
|
||||
break;
|
||||
}
|
||||
}
|
||||
thisRow.push(thisCell);
|
||||
}
|
||||
result.push([thisRowExample, thisRow]);
|
||||
}
|
||||
|
||||
// Add Subtotal
|
||||
const subtotalRow = [];
|
||||
let subtotalExample = null;
|
||||
for (let cell of row[1]) {
|
||||
let thisCell = null;
|
||||
for (let entry of (cell as any).entries) {
|
||||
if (entry instanceof Subtotal) {
|
||||
thisCell = entry;
|
||||
subtotalExample = entry;
|
||||
break;
|
||||
}
|
||||
}
|
||||
subtotalRow.push(thisCell);
|
||||
}
|
||||
if (subtotalExample) {
|
||||
result.push([subtotalExample, subtotalRow]);
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
</script>
|
@ -23,7 +23,8 @@
|
||||
<a :href="entry.LiteralRow.link" class="hover:text-blue-700 hover:underline" v-if="entry.LiteralRow.link !== null">{{ entry.LiteralRow.text }}</a>
|
||||
<template v-if="entry.LiteralRow.link === null">{{ entry.LiteralRow.text }}</template>
|
||||
</component>
|
||||
<component :is="entry.LiteralRow.heading ? 'th' : 'td'" class="py-0.5 pl-1 text-gray-900 text-end" :class="{ 'font-semibold': entry.LiteralRow.heading }" v-html="ppBracketed(entry.LiteralRow.quantity, entry.LiteralRow.link ?? undefined)" />
|
||||
<component :is="entry.LiteralRow.heading ? 'th' : 'td'" class="py-0.5 pl-1 text-gray-900 text-end" :class="{ 'font-semibold': entry.LiteralRow.heading }" v-html="(cell !== 0 || entry.LiteralRow.heading) ? ppBracketed(cell, entry.LiteralRow.link ?? undefined) : ''" v-for="cell of entry.LiteralRow.quantity">
|
||||
</component>
|
||||
</tr>
|
||||
</template>
|
||||
<template v-if="entry.Section">
|
||||
|
@ -16,11 +16,9 @@
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
-->
|
||||
|
||||
<!-- Report display -->
|
||||
|
||||
<template>
|
||||
<DynamicReportComponent :report="report">
|
||||
<!-- <div class="my-2 py-2 flex">
|
||||
<div class="my-2 py-2 flex">
|
||||
<div class="grow flex gap-x-2 items-baseline">
|
||||
<span class="whitespace-nowrap">As at</span>
|
||||
<input type="date" class="bordered-field" v-model.lazy="dt">
|
||||
@ -45,120 +43,81 @@
|
||||
<p class="text-sm text-red-700">Total assets do not equal total liabilities and equity. This may occur if not all accounts have been classified in the chart of accounts.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div> -->
|
||||
</div>
|
||||
</DynamicReportComponent>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import dayjs from 'dayjs';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { ref } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import DynamicReport from './base.ts';
|
||||
import { ExclamationCircleIcon } from '@heroicons/vue/20/solid';
|
||||
|
||||
import { DynamicReport, reportEntryById } from './base.ts';
|
||||
import { db } from '../db.ts';
|
||||
import { ExtendedDatabase } from '../dbutil.ts';
|
||||
import DynamicReportComponent from '../components/DynamicReportComponent.vue';
|
||||
|
||||
const report = ref(null as DynamicReport | null);
|
||||
|
||||
const dt = ref(null as string | null);
|
||||
const comparePeriods = ref(1);
|
||||
const compareUnit = ref('years');
|
||||
|
||||
async function load() {
|
||||
report.value = JSON.parse(await invoke('get_balance_sheet', {}));
|
||||
console.log(report.value);
|
||||
const session = await db.load();
|
||||
|
||||
dt.value = db.metadata.eofy_date;
|
||||
|
||||
await updateReport(session);
|
||||
|
||||
// Update report when dates etc. changed
|
||||
// We initialise the watcher here only after dt is initialised above
|
||||
watch([dt, comparePeriods, compareUnit], async () => {
|
||||
const session = await db.load();
|
||||
await updateReport(session);
|
||||
});
|
||||
}
|
||||
load();
|
||||
|
||||
// import { computed, ref, watch } from 'vue';
|
||||
// import dayjs from 'dayjs';
|
||||
async function updateReport(session: ExtendedDatabase) {
|
||||
const reportDates = [];
|
||||
for (let i = 0; i < comparePeriods.value; i++) {
|
||||
let thisReportDt;
|
||||
|
||||
// import { ExclamationCircleIcon } from '@heroicons/vue/20/solid';
|
||||
// Get period end date
|
||||
if (compareUnit.value === 'years') {
|
||||
thisReportDt = dayjs(dt.value!).subtract(i, 'year');
|
||||
} else if (compareUnit.value === 'months') {
|
||||
if (dayjs(dt.value!).add(1, 'day').isSame(dayjs(dt.value!).set('date', 1).add(1, 'month'))) {
|
||||
// If dt is the end of a calendar month, then fix each prior dt to be the end of the calendar month
|
||||
thisReportDt = dayjs(dt.value!).subtract(i, 'month').set('date', 1).add(1, 'month').subtract(1, 'day');
|
||||
} else {
|
||||
thisReportDt = dayjs(dt.value!).subtract(i, 'month');
|
||||
}
|
||||
} else {
|
||||
throw new Error('Unexpected compareUnit');
|
||||
}
|
||||
|
||||
// import { Computed, DynamicReport, Entry, Section, Spacer, Subtotal } from './base.ts';
|
||||
// import { IncomeStatementReport} from './IncomeStatementReport.vue';
|
||||
// import { db } from '../db.ts';
|
||||
// import { ExtendedDatabase } from '../dbutil.ts';
|
||||
// import ComparativeDynamicReportComponent from '../components/ComparativeDynamicReportComponent.vue';
|
||||
// import { ReportingStage, ReportingWorkflow } from '../reporting.ts';
|
||||
reportDates.push(thisReportDt.format('YYYY-MM-DD'));
|
||||
}
|
||||
|
||||
// const reports = ref([] as BalanceSheetReport[]);
|
||||
// const reportLabels = ref([] as string[]);
|
||||
report.value = JSON.parse(await invoke('get_balance_sheet', { eofyDate: db.metadata.eofy_date, dates: reportDates }));
|
||||
}
|
||||
|
||||
// const dt = ref(null as string | null);
|
||||
// const comparePeriods = ref(1);
|
||||
// const compareUnit = ref('years');
|
||||
const doesBalance = computed(function() {
|
||||
const totalAssets = reportEntryById(report.value, 'total_assets').LiteralRow.quantity;
|
||||
const totalLiabilities = reportEntryById(report.value, 'total_liabilities').LiteralRow.quantity;
|
||||
const totalEquity = reportEntryById(report.value, 'total_equity').LiteralRow.quantity;
|
||||
|
||||
// async function load() {
|
||||
// const session = await db.load();
|
||||
|
||||
// dt.value = db.metadata.eofy_date;
|
||||
|
||||
// await updateReport(session);
|
||||
|
||||
// // Update report when dates etc. changed
|
||||
// // We initialise the watcher here only after dt and dtStart are initialised above
|
||||
// watch([dt, comparePeriods, compareUnit], async () => {
|
||||
// const session = await db.load();
|
||||
// await updateReport(session);
|
||||
// });
|
||||
// }
|
||||
// load();
|
||||
|
||||
// async function updateReport(session: ExtendedDatabase) {
|
||||
// const newReportPromises = [];
|
||||
// const newReportLabels = [];
|
||||
// for (let i = 0; i < comparePeriods.value; i++) {
|
||||
// let thisReportDt, thisReportLabel;
|
||||
|
||||
// // Get period end date
|
||||
// if (compareUnit.value === 'years') {
|
||||
// thisReportDt = dayjs(dt.value!).subtract(i, 'year');
|
||||
// thisReportLabel = dayjs(dt.value!).subtract(i, 'year').format('YYYY');
|
||||
// } else if (compareUnit.value === 'months') {
|
||||
// if (dayjs(dt.value!).add(1, 'day').isSame(dayjs(dt.value!).set('date', 1).add(1, 'month'))) {
|
||||
// // If dt is the end of a calendar month, then fix each prior dt to be the end of the calendar month
|
||||
// thisReportDt = dayjs(dt.value!).subtract(i, 'month').set('date', 1).add(1, 'month').subtract(1, 'day');
|
||||
// } else {
|
||||
// thisReportDt = dayjs(dt.value!).subtract(i, 'month');
|
||||
// }
|
||||
// thisReportLabel = dayjs(dt.value!).subtract(i, 'month').format('YYYY-MM');
|
||||
// } else {
|
||||
// throw new Error('Unexpected compareUnit');
|
||||
// }
|
||||
|
||||
// // Get start of financial year date
|
||||
// let sofyDayjs = dayjs(db.metadata.eofy_date).subtract(1, 'year').add(1, 'day');
|
||||
// let thisReportDtStart = thisReportDt.set('date', sofyDayjs.get('date')).set('month', sofyDayjs.get('month'));
|
||||
// if (thisReportDtStart.isAfter(thisReportDt)) {
|
||||
// thisReportDtStart = thisReportDtStart.subtract(1, 'year');
|
||||
// }
|
||||
|
||||
// console.log([thisReportDt, thisReportDtStart]);
|
||||
|
||||
// // Generate reports asynchronously
|
||||
// newReportPromises.push((async () => {
|
||||
// const reportingWorkflow = new ReportingWorkflow();
|
||||
// await reportingWorkflow.generate(session, thisReportDt.format('YYYY-MM-DD'), thisReportDtStart.format('YYYY-MM-DD'));
|
||||
// return reportingWorkflow.getReportAtStage(ReportingStage.FINAL_STAGE, BalanceSheetReport) as BalanceSheetReport;
|
||||
// })());
|
||||
|
||||
// if (comparePeriods.value === 1) {
|
||||
// // If only 1 report, the heading is simply "$"
|
||||
// newReportLabels.push(db.metadata.reporting_commodity);
|
||||
// } else {
|
||||
// newReportLabels.push(thisReportLabel);
|
||||
// }
|
||||
// }
|
||||
|
||||
// reports.value = await Promise.all(newReportPromises);
|
||||
// reportLabels.value = newReportLabels;
|
||||
// }
|
||||
|
||||
// const doesBalance = computed(function() {
|
||||
// let doesBalance = true;
|
||||
// for (const report of reports.value) {
|
||||
// const totalAssets = (report.byId('total_assets') as Computed).quantity;
|
||||
// const totalLiabilities = (report.byId('total_liabilities') as Computed).quantity;
|
||||
// const totalEquity = (report.byId('total_equity') as Computed).quantity;
|
||||
// if (totalAssets !== totalLiabilities + totalEquity) {
|
||||
// doesBalance = false;
|
||||
// }
|
||||
// }
|
||||
// return doesBalance;
|
||||
// });
|
||||
let doesBalance = true;
|
||||
for (let column = 0; column < report.value.columns.length; column++) {
|
||||
if (totalAssets[column] !== totalLiabilities[column] + totalEquity[column]) {
|
||||
doesBalance = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return doesBalance;
|
||||
});
|
||||
</script>
|
||||
|
@ -1,6 +1,6 @@
|
||||
/*
|
||||
DrCr: Web-based double-entry bookkeeping framework
|
||||
Copyright (C) 2022–2024 Lee Yingtong Li (RunasSudo)
|
||||
Copyright (C) 2022-2025 Lee Yingtong Li (RunasSudo)
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
@ -16,8 +16,7 @@
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { db, getAccountsForKind } from '../db.ts';
|
||||
|
||||
// Cannot be a class as these are directly deserialised from JSON
|
||||
export interface DynamicReport {
|
||||
title: string;
|
||||
columns: string[];
|
||||
@ -25,13 +24,13 @@ export interface DynamicReport {
|
||||
}
|
||||
|
||||
// serde_json serialises an enum like this
|
||||
export type DynamicReportEntry = {Section: Section} | {LiteralRow: LiteralRow} | 'Spacer';
|
||||
export type DynamicReportEntry = { Section: Section } | { LiteralRow: LiteralRow } | 'Spacer';
|
||||
|
||||
export interface Section {
|
||||
text: string;
|
||||
id: string | null;
|
||||
visible: bool;
|
||||
auto_hide: bool;
|
||||
visible: boolean;
|
||||
auto_hide: boolean;
|
||||
entries: DynamicReportEntry[];
|
||||
}
|
||||
|
||||
@ -39,12 +38,28 @@ export interface LiteralRow {
|
||||
text: string;
|
||||
quantity: number[];
|
||||
id: string;
|
||||
visible: bool;
|
||||
auto_hide: bool;
|
||||
visible: boolean;
|
||||
auto_hide: boolean;
|
||||
link: string | null;
|
||||
heading: bool;
|
||||
bordered: bool;
|
||||
heading: boolean;
|
||||
bordered: boolean;
|
||||
}
|
||||
|
||||
export interface Spacer {
|
||||
}
|
||||
|
||||
export function reportEntryById(report: DynamicReport | Section, id: string): DynamicReportEntry | null {
|
||||
for (const entry of report.entries) {
|
||||
if ((entry as { Section: Section }).Section) {
|
||||
const result = reportEntryById((entry as { Section: Section }).Section, id);
|
||||
if (result !== null) {
|
||||
return result;
|
||||
}
|
||||
} else if ((entry as { LiteralRow: LiteralRow }).LiteralRow) {
|
||||
if ((entry as { LiteralRow: LiteralRow }).LiteralRow.id === id) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user