<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-03-22T01:57:59.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-03-22T01:55:33.8030000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2023-03-22T01:57:41.1210000</UpdatedUtcDate>
    <ScriptId>QQTHW</ScriptId>
    <Description>Quick Quote (Term) Widget</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_QuickQuoteTerm
Option Explicit On
Option Strict On

' #################################################################
' Quick Quote (Term) HTML Widget
'
' Version: 1.05 (22/03/2023)
'
' Usage: Sample HTML Widget
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.05  22/03/2023  ISS       J030745  Change event handling in template text
' #################################################################

' Objects
Private mCombinedParameters As ISKeyValueList
Private mParameters As ISKeyValueList
Private mStartupParameters As ISKeyValueList

Public Function Main(eventId As String, parametersJson As String, startUpParametersJson As String, hostingContext As isefinHtmlWidgetHostingContext, requestInfo As finScriptRequestInfo, ByRef returnValue As String) As Boolean

  ' Assume Success
  Main = True

  ' Get Parameters
  mParameters = finBL.CreateKeyValueList()
  mParameters.FromSimpleJsonString(parametersJson)
  mStartupParameters = finBL.CreateKeyValueList()
  mStartupParameters.FromSimpleJsonString(startUpParametersJson)

  ' Get Combined Parameters (Startup Parameters updated with event Parameters)
  mCombinedParameters = mStartupParameters.Clone()
  mCombinedParameters.UpdateFromKeyValueList(mParameters, True)

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return initial HTML content (excluding html and body tags)
      returnValue = GetPage()

    Case "Calculate"
      ' Calculate
      Main = Calculate(parametersJson, returnValue)
  End Select

End Function

Private Function GetPage() As String

  Dim AccountType As finAccountTypeRO
  Dim AccountTypeDetails As List(Of AccountTypeDetail)
  Dim AccountTypeDetailsJson As String
  Dim DefaultAccountTypeId As String
  Dim DefaultTerm As String
  Dim Html As String
  Dim LoanAmount As Decimal
  Dim TermList As ISList

  ' Initialise
  Html = ScriptInfo.TemplateText

  ' Create Objects
  TermList = New ISList()

  ' Create a list of available Term-based Loan Account Types
  AccountTypeDetails = New List(Of AccountTypeDetail)
  For Each AccountType In finBL.AccountTypes
    If AccountType.Active AndAlso AccountType.TermEntryMethod = isefinAccountTermEntryMethod.Term Then
      Select Case AccountType.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
          ' Get Term List ensuring that Default Term exists in this List
          TermList.FromCsvString(AccountType.TermListResolved)
          DefaultTerm = finBL.Utilities.DateCycleGetDescription(False, AccountType.Term)
          If Not TermList.Exists(DefaultTerm) Then TermList.Add(DefaultTerm)

          ' Get default Loan Amount
          If AccountType.StandardTransactions.Count &gt; 0 Then
            LoanAmount = AccountType.StandardTransactions(0).ValueCurrency
          Else
            LoanAmount = 0
          End If

          ' Add Item
          AccountTypeDetails.Add(New AccountTypeDetail(AccountType.AccountTypeId,
                                                       AccountType.Description,
                                                       TermList.ToCsvString(),
                                                       LoanAmount,
                                                       DefaultTerm))
      End Select
    End If
  Next
  finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(AccountTypeDetails, AccountTypeDetailsJson)

  ' Get Default Account Type
  DefaultAccountTypeId = mStartupParameters.GetString("AccountTypeId")
  If Len(DefaultAccountTypeId) = 0 Then
    If Len(finBL.SettingsUser.DefaultAccountProductTypeId) &lt;&gt; 0 Then
      DefaultAccountTypeId = finBL.ProductTypes(finBL.SettingsUser.DefaultAccountProductTypeId).DefaultAccountTypeId

      ' Ensure Term-based
      If Len(DefaultAccountTypeId) &lt;&gt; 0 AndAlso finBL.AccountTypes(DefaultAccountTypeId).TermEntryMethod &lt;&gt; isefinAccountTermEntryMethod.Term Then
        DefaultAccountTypeId = ""
      End If
    End If
  End If

  ' Replace Tags
  Html = replace(Html, "&lt;%[AccountTypes]%&gt;", AccountTypeDetailsJson)
  Html = replace(Html, "&lt;%[DefaultAccountTypeId]%&gt;", DefaultAccountTypeId)
  Html = replace(Html, "&lt;%[ShowAccountType]%&gt;", lCase(CStr(mStartupParameters.GetBoolean("ShowAccountType"))))

  Return Html

End Function

Private Function Calculate(parametersJson As String,
                           ByRef returnValue As String) As Boolean

  Dim Account As finAccount
  Dim AccountType As finAccountTypeRO
  Dim Amount As Decimal
  Dim CalculationDetails As CalculationDetails
  Dim kvl As ISKeyValueList
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTablesTermAndPayments As ISSummaryTables
  Dim Term As String

  ' Assume Success
  Success = True

  ' Parse Parameters
  ' NOTE: Since this is a simple, flat, JSON object, it can be directly parsed into a Key/ Value List
  kvl = finBL.CreateKeyValueList()
  Calculate = kvl.FromSimpleJsonString(parametersJson)

  ' Get Parameters
  ' NOTE: Use the module mCombinedParameters since this contains Startup and event Parameters in a single Key/Value List
  With mCombinedParameters
    AccountType = GetAccountType(.GetString("AccountTypeId"))
    Amount = .GetDecimal("Amount")
    Term = .GetString("Term")
  End With

  ' Validate
  If Success Then
    If AccountType Is Nothing Then
      Success = False
      finBL.Error.ErrorBegin("Invalid Account Type.")
    Else
      With AccountType
        If .TermEntryMethod &lt;&gt; isefinAccountTermEntryMethod.Term Then
          Success = False
          finBL.Error.ErrorBeginFormat("Account Type '{0}' must have a Term Entry Method of 'Term'.", AccountType.AccountTypeId)
        End If
      End With
    End If
  End If

  ' Calculate
  If Success Then
    ' Create Account
    Account = finBL.CreateAccount()

    ' Configure
    With Account.Calculation
      If .LoadAccountType(AccountType.AccountTypeId) Then
        .StandardTransactions.SetAdvance(Amount)
        .TermCycle = Term
      Else
        Success = False
      End If
    End With

    ' Calculate
    If Success Then
      Success = Account.Calculation.Calculate()
    End If
  End If

  ' Return Calculation Details (including an HTML Summary)
  If Success Then
    ' Initialise
    CalculationDetails = New CalculationDetails()

    ' Set Properties
    With CalculationDetails
      .PaymentRegular = Account.Calculation.PaymentRegular
    End With

    ' Generate HTML Summary
    ' NOTE: Simply return the built-in Term and Payments Summary
    sb = finBL.CreateHtmlSummaryPage2StringBuilder()
    With sb
      .Initialise(iseSummaryPageTarget.WebInternal, False, False, True)

      ' General
      SummaryTable = finBL.CreateSummaryTable()
      With SummaryTable
        .TableClass = iseSummaryTableClass.Information
        .Columns.AddText()
        .Columns.AddText()

        With .Rows
          .AddSectionHeading2("Account details")
          .AddCaptionCodeDescription("Account Type:", AccountType.AccountTypeId, AccountType.Description)
        End With
      End With
      .SummaryTableAppend(SummaryTable, "auto")

      ' Term &amp; Payments
      SummaryTablesTermAndPayments = finBL.SummaryPageStandardBlocks().Account_TermAndPayments(ScriptInfo, Account, 0, False, Nothing)
      .SummaryTablesAppend(SummaryTablesTermAndPayments)

      ' Finalise and set first column widths to match
      With SummaryTablesTermAndPayments.ItemByIndex(0).Columns(0)
        SummaryTable.Columns(0).WidthChars = .WidthChars
        SummaryTable.Columns(0).WidthHtml = .WidthHtml
      End With
      .HtmlFinalise()
    End With
    CalculationDetails.Html = sb.ToString(True)

    ' Return a JSON Object
    Success = finBL.Runtime.WebUtilities.SerialiseObjectToJsonString(CalculationDetails, returnValue)
  End If

  Return Success

End Function

Private Function GetAccountType(accountTypeId As String) As finAccountTypeRO

  ' Account Type is determined firstly from the value supplied, then from the Widget parameters, then from the Startup parameters and finally from User Preferences
  If Len(accountTypeId) = 0 Then accountTypeId = mStartupParameters.GetString("AccountTypeId")
  If Len(accountTypeId) = 0 Then accountTypeId = mParameters.GetString("AccountTypeId")
  If Len(accountTypeId) = 0 Then
    If Len(finBL.SettingsUser.DefaultAccountProductTypeId) &lt;&gt; 0 Then
      accountTypeId = finBL.ProductTypes(finBL.SettingsUser.DefaultAccountProductTypeId).DefaultAccountTypeId
    End If
  End If

  If finBL.AccountTypes.Exists(accountTypeId) Then
    Return finBL.AccountTypes(accountTypeId)
  Else
    Return Nothing
  End If

End Function


Public Class AccountTypeDetail

  Public AccountTypeId As String
  Public Description As String
  Public TermList As String
  Public LoanAmount As Decimal
  Public DefaultTerm As String

  Public Sub New(accountTypeId As String,
                 description As String,
                 termList As String,
                 loanAmount As Decimal,
                 defaultTerm As String)

    Me.AccountTypeId = accountTypeId
    Me.Description = description
    Me.TermList = termList
    Me.LoanAmount = loanAmount
    Me.DefaultTerm = defaultTerm
  End Sub

End Class


Public Class CalculationDetails

  Public Html As String
  Public PaymentRegular As Decimal

End Class</Code>
    <Language>VisualBasic</Language>
    <Notes>Sample HTML Widget to provide a Quick Quote for Term-based Account Types.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;div id="frmMain" class="is-widget-content is-widget-form-body"&gt;

  &lt;table class="is-form"&gt;
    &lt;tr id="trAccountType" style="display:none"&gt;
      &lt;th&gt;&lt;label for="cboAccountType"&gt;Account Type:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;select id="cboAccountType" mandatory="true"&gt;&lt;/select&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="numAmount"&gt;Amount:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;input id="numAmount" mandatory="true" field-type="currency" blank-if-zero="true"/&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;&lt;label for="cboTerm"&gt;Term:&lt;/label&gt;&lt;/th&gt;
      &lt;td&gt;&lt;select id="cboTerm" mandatory="true"&gt;&lt;/select&gt;
    &lt;/tr&gt;
  &lt;/table&gt;

  &lt;br/&gt;
  &lt;button id="cmdCalculate" class="is-button ok"&gt;Calculate&lt;/button&gt;
  &lt;button id="cmdReset" class="is-button"&gt;Reset&lt;/button&gt;
  &lt;button id="cmdClose" class="is-button"&gt;Close&lt;/button&gt;

  &lt;hr/&gt;

  &lt;div id="divResults" class="is-summarypage-2"&gt;&lt;/div&gt;

&lt;/div&gt;


&lt;script&gt;
// Server-side information
var mAccountTypes = &lt;%[AccountTypes]%&gt;;
var mDefaultAccountTypeId = "&lt;%[DefaultAccountTypeId]%&gt;";
var mShowAccountType = &lt;%[ShowAccountType]%&gt;;

// Objects
var mCalculationDetails;
var mSelectedAccountType;

// Form
var frmMain;

// HTML Elements
var divResults;

// Initialise
$(function () {
  // Create Widget form
  frmMain = new widget.UI.Form("frmMain", { captionWidth: "8em", textboxWidth: "20em" });

  // Controls
  $("#cboAccountType").change(cboAccountType_Change);

  // Account Types List
  widget.UI.DDListFromCollection("cboAccountType", mAccountTypes, "Description", "AccountTypeId");
  cboAccountType.value = mDefaultAccountTypeId;
  if(cboAccountType.selectedIndex == -1 &amp;&amp; mAccountTypes.length != 0) cboAccountType.selectedIndex = 0;
  cboAccountType_Change();

  // Show Account Type Selection?
  if (mShowAccountType) $("#trAccountType").show();

  // Get HTML Elements
  divResults = $("#divResults");

  // Handle Buttons
  $("#cmdCalculate").click(Calculate);
  $("#cmdReset").click(function() {widget.Reset();});
  $("#cmdClose").click(function() {widget.Close();});
  if(!widget.CanClose()) $("#cmdClose").hide();
});

// ==============
// cboAccountType
// ==============
function cboAccountType_Change(sender, e) {
  // Handled
  if (e) e.ChangeHandled = true;
  
  // Just in case!
  if (cboAccountType.selectedIndex == -1) return;

  // Get Account Type
  mAccountType = mAccountTypes[cboAccountType.selectedIndex];

  // Update Term and default Amount
  widget.UI.DDListFromCsv("cboTerm", mAccountType.TermList, mAccountType.DefaultTerm);
  cboTerm.value = mAccountType.DefaultTerm;
  numAmount.value = widget.FormatCurrency(mAccountType.LoanAmount, false, true);
}

// =========
// Calculate
// =========
function Calculate() {
  // Create object
  var o = {};
  o.AccountTypeId = cboAccountType.value;
  o.Amount = numAmount.value;
  o.Term = cboTerm.value;

  // Validate
  if (!o.AccountTypeId) {
    window.alert("Account Type not entered.");
    cboAccountType.focus();
    return;
  }
  else if (!o.Amount) {
    window.alert("Amount not entered.");
    numAmount.focus();
    return;
  }
  else if (!o.Term) {
    window.alert("Term not entered.");
    cboTerm.focus();
    return;
  }

  // Calculate
  widget.GetString("Calculate", o, Calculate_Done, Calculate_Fail);
}

function Calculate_Done(data) {
  // Parse and Save Calculation Details
  mCalculationDetails = JSON.parse(data);

  // Show Summary
  divResults.html(mCalculationDetails.Html);
}

function Calculate_Fail(errorMessage) {
  divResults.text(errorMessage);
}
&lt;/script&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>VVBwRXv28U6Q9K9lP6GCMg</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Quick Quote (Term)</Caption>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>0</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>true</HtmlWidgetResourceCssWidget>
    <HtmlWidgetResourceJQuery>true</HtmlWidgetResourceJQuery>
    <HtmlWidgetResourceJQueryVersion />
    <HtmlWidgetSpecialEventGetFolderCount>false</HtmlWidgetSpecialEventGetFolderCount>
    <Icon>Calculator</Icon>
    <RestrictedOriginsListEnabled>false</RestrictedOriginsListEnabled>
    <RunAsAdministrator>false</RunAsAdministrator>
    <WebServiceName />
    <WebServiceAllowAnonymous>false</WebServiceAllowAnonymous>
    <WebServiceSendDebugInformation>true</WebServiceSendDebugInformation>
    <ShowInMenu>None</ShowInMenu>
    <ParametersType>Custom</ParametersType>
    <Parameters>
      <ISParameterDefs version="1.00">
        <Parameters>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Select the default Account Type.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText>Leave blank to use the Account Type defined under Tools, User Preferences, Accounts, General (the Account Type is defined by the default Product Type).</TooltipText>
            <SectionColumns>1</SectionColumns>
            <Visible>false</Visible>
          </Parameter>
          <Parameter name="AccountTypeId" type="Range">
            <BlankTip />
            <Caption>Account Type:</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <Mandatory>false</Mandatory>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value />
            <Visible>true</Visible>
            <LimitToList>true</LimitToList>
            <MaxLength>10</MaxLength>
            <RangeSingle>true</RangeSingle>
            <RangeType>Standard</RangeType>
            <RangeLookupSource>AccountTypesLoans</RangeLookupSource>
            <RangeLookupSqlWhere />
          </Parameter>
          <Parameter name="" type="SectionStart">
            <BlankTip />
            <Caption>Specify options to show.</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <SectionColumns>1</SectionColumns>
            <Visible>false</Visible>
          </Parameter>
          <Parameter name="ShowAccountType" type="Boolean">
            <BlankTip />
            <Caption>Show Account Type selection?</Caption>
            <StandaloneOnly>false</StandaloneOnly>
            <TooltipText />
            <DefaultValueExpression />
            <Enabled>true</Enabled>
            <HideDescription>false</HideDescription>
            <IndentLevel>0</IndentLevel>
            <NonPersistable>false</NonPersistable>
            <ReadOnly>false</ReadOnly>
            <ReadOnly2>false</ReadOnly2>
            <Value>True</Value>
            <Visible>true</Visible>
          </Parameter>
        </Parameters>
      </ISParameterDefs>
    </Parameters>
  </finScript>