In my Memento Database library "SALES REPORT" I have an embedded object field named "DEBIT ACCOUNT" with two attributes: "ACCOUNT NAME" and "AMOUNT". This library also includes a JavaScript field called "BALANCE" I have another library, "ACCOUNT REPORT" with the fields "ACCOUNT NAME", "OPENING BALANCE" , "Dr", "Cr" and "CLOSING BALANCE".
I want the JavaScript field ( " BALANCE" ) in the "SALES REPORT" library to retrieve and display the most recent "Closing Balance" from the "Account Report" library for the account selected in the "Debit Account" field. If multiple accounts are selected, the "Balance" field should show the balances for all chosen accounts.
Script :
// Get the embedded object field "Debit Account"
var debitAccounts = entry().field("DEBIT ACCOUNT")
// Initialize an array to store balance information
var balances = [];
// Access the "Account Report" library
var accountLib = libByName("ACCOUNT REPORT");
// Check if debitAccounts is not empty
if (debitAccounts && debitAccounts.length > 0) {
// Iterate through each selected debit account
for (var i = 0; i < debitAccounts.length; i++) {
var accountName = debitAccounts[i].field("ACCOUNT NAME");
// Find the latest entry in "Account Report" for this account name
var accountEntries = accountLib.entries()
.filter(function(e) { return e.field("ACCOUNT NAME") === accountName; })
.sort(function(a, b) { return b.getCreatedAt() - a.getCreatedAt(); });
// Get the closing balance from the latest entry
if (accountEntries.length > 0) {
var closingBalance = accountEntries[0].field("CLOSING BALANCE");
balances.push(accountName + ": " + closingBalance);
} else {
balances.push(accountName + ": No balance found");
}
}
// Return the balances as a formatted string
result = balances.join("\n");
} else {
result = "No accounts selected";
}
// Output the result
result;
I have tried this script generated from AI. But it is showing an error "libByName is not defined" . Please help me with the script if possible.
Thanks.