<?xml version="1.0" encoding="utf-8"?>
  <finScript version="1.00" exportedUtcDate="2023-03-22T01:56:59.0000000">
    <CreatedUserId>Admin</CreatedUserId>
    <CreatedUtcDate>2023-03-22T01:49:57.7120000</CreatedUtcDate>
    <UpdatedUserId>Admin</UpdatedUserId>
    <UpdatedUtcDate>2023-03-22T01:56:48.1280000</UpdatedUtcDate>
    <ScriptId>CQHW</ScriptId>
    <Description>Client Quote</Description>
    <ScriptType>HtmlWidget</ScriptType>
    <Active>true</Active>
    <AllowUI>false</AllowUI>
    <Bookmarks />
    <Category />
    <Code>' HtmlWidget_ClientQuote
Option Explicit On
Option Strict On

' #################################################################
' Client Quote HTML Widget
'
' Version: 1.05 (22/03/2023)
'
' Usage: Sample HTML Widget
'
' NOTE:
' -----
' This is designed to be run from a system such as Client Connect.
' If not signed in as a Client, no "Apply" button will show.
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    1.05  22/03/2023  ISS       J030745  Change event handling in template text
' #################################################################


'#Const "AccountRoleId",String,"B","The Account Role to assign when adding a Client to an Account."

' Constants
Private AccountRoleId As String = "B"

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

' Other
Private mClientId As String

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)

  ' Get Constants
  With ScriptInfo.Constants
    AccountRoleId = .GetString("AccountRoleId", AccountRoleId)
  End With

  ' Other
  mClientId = requestInfo.AuthenticatedClientId

  ' Handle Events
  If Main Then
    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)

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

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 DefaultPaymentFreq As String
  Dim Html As String
  Dim LoanAmount As Decimal
  Dim PaymentFreqsList As ISList

  ' Initialise
  Html = ScriptInfo.TemplateText

  ' Create Objects
  PaymentFreqsList = New ISList()

  ' Create a list of available No. of Payments based Loan Account Types
  AccountTypeDetails = New List(Of AccountTypeDetail)
  For Each AccountType In finBL.AccountTypes
    If AccountType.Active AndAlso AccountType.TermEntryMethod = isefinAccountTermEntryMethod.NumberOfPayments Then
      Select Case AccountType.AccountClass
        Case isefinAccountClass.LoanFR, isefinAccountClass.LoanFT, isefinAccountClass.LoanRC
          ' Get Payment Frequecies List ensuring that Default exists in this List
          PaymentFreqsList.FromCsvString(AccountType.PaymentCycleListResolved)
          DefaultPaymentFreq = finBL.Utilities.DateCycleGetDescription(True, AccountType.PaymentCycle)
          If Not PaymentFreqsList.Exists(DefaultPaymentFreq) Then PaymentFreqsList.Add(DefaultPaymentFreq)

          ' 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,
                                                       PaymentFreqsList.ToCsvString(),
                                                       LoanAmount,
                                                       AccountType.TermNumberOfPayments,
                                                       DefaultPaymentFreq))
      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
    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"))))
  Html = replace(Html, "&lt;%[ClientId]%&gt;", mClientId)

  Return Html

End Function

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

  Dim Account As finAccount
  Dim CalculationDetails As CalculationDetails
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim Success As Boolean
  Dim SummaryTableAccountDetails As ISSummaryTable
  Dim SummaryTablesTermAndPayments As ISSummaryTables

  ' Assume Success
  Success = True

  ' Calculate
  Success = CalculateInternal(parametersJson, returnValue, Account)

  ' 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
      SummaryTableAccountDetails = finBL.CreateSummaryTable()
      With SummaryTableAccountDetails
        .TableClass = iseSummaryTableClass.Information
        .Columns.AddText()
        .Columns.AddText()

        With .Rows
          .AddSectionHeading2("Account details")
          .AddCaptionCodeDescription("Account Type:", Account.AccountTypeId, finBL.AccountTypes)
        End With
      End With

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

      ' Finalise and set first column widths to match
      With SummaryTablesTermAndPayments.ItemByIndex(0).Columns(0)
        SummaryTableAccountDetails.Columns(0).WidthChars = .WidthChars
        SummaryTableAccountDetails.Columns(0).WidthHtml = .WidthHtml
      End With

      ' Render Tables
      .SummaryTableAppend(SummaryTableAccountDetails, "100%")
      .SummaryTablesAppend(SummaryTablesTermAndPayments)

      .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 CalculateInternal(parametersJson As String,
                             ByRef returnValue As String,
                             ByRef account As finAccount) As Boolean

  Dim AccountType As finAccountTypeRO
  Dim Amount As Decimal
  Dim kvl As ISKeyValueList
  Dim PaymentFreq As String
  Dim Payments As Integer
  Dim Success As Boolean

  ' 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()
  Success = 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")
    PaymentFreq = .GetString("PaymentFreq")
    Payments = .GetInteger("Payments")
  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.NumberOfPayments Then
          Success = False
          finBL.Error.ErrorBeginFormat("Account Type '{0}' must have a Term Entry Method of 'Number of Payments'.", 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)
        .PaymentCycle = PaymentFreq
        .TermNumberOfPayments = Payments
      Else
        Success = False
      End If
    End With

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

  Return Success

End Function

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

  Dim Account As finAccount
  Dim AccountClient As finAccountClient
  Dim Success As Boolean

  ' Calculate
  Success = CalculateInternal(parametersJson, returnValue, Account)

  ' Add Client and Save
  If Success Then
    With Account
      ' Create Client
      AccountClient = .Clients.CreateAccountClient()
      With AccountClient
        .ClientIdSet(mClientId)
        .AccountRoleIdSet(AccountRoleId)
      End With

      ' Add Client
      .Clients.Add(AccountClient)

      ' Update Account details
      .Name = AccountClient.ClientName
      .Description = .CreateDescription()

      ' Save
      If .Save() Then
        returnValue = Account.AccountId
      Else
        Success = False
      End If
    End With
  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 PaymentFreqsList As String
  Public LoanAmount As Decimal
  Public DefaultPayments As Integer
  Public DefaultPaymentFreq As String

  Public Sub New(accountTypeId As String,
                 description As String,
                 paymentFreqsList As String,
                 loanAmount As Decimal,
                 defaultPayments As Integer,
                 defaultPaymentFreq As String)

    Me.AccountTypeId = accountTypeId
    Me.Description = description
    Me.PaymentFreqsList = paymentFreqsList
    Me.LoanAmount = loanAmount
    Me.DefaultPayments = defaultPayments
    Me.DefaultPaymentFreq = defaultPaymentFreq
  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 No. of Payments-based Account Types and, if logged in as a Client, the ability to add a "Quote" Account.

This is used in the "Apply for Loan" section in the Client Connect sample.

This sample uses Sementic UI so that the input form can be styled as per Client Connect 3.</Notes>
    <PermissionKeyExecute />
    <RunWithoutPrompts>false</RunWithoutPrompts>
    <TemplateText>&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;!-- Semantic UI --&gt;
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt;
	&lt;script src="https://cdn.jsdelivr.net/semantic-ui/2.2.6/semantic.min.js"&gt;&lt;/script&gt;
	&lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.6/semantic.min.css"&gt;

  &lt;style&gt;
    @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,600,700);
    #divResults {
      background-color:rgba(0,0,0,0.025);
      border:1px solid rgba(0,0,0,0.05);
      border-radius:8px;
      margin-top:12px;
      padding:8px;
      font-size:0.9em;
      font-family:font-family:'Open Sans', Sans-serif, 'Helvetica Neue', Helvetica, Verdana, Arial !important;
    }
    #divResults:empty {display:none;}
  &lt;/style&gt;
&lt;/head&gt;
&lt;body class="is-widget-content"&gt;

  &lt;div id="frmMain"&gt;
  &lt;div role="form" class="ui form"&gt;
    &lt;div id="trAccountType" class="field" style="display:none"&gt;
      &lt;label&gt;Loan Type&lt;/label&gt;
      &lt;select id="cboAccountType" mandatory="true"&gt;&lt;/select&gt;
    &lt;/div&gt;

    &lt;div class="field"&gt;
      &lt;label&gt;Amount&lt;/label&gt;
      &lt;input id="numAmount" mandatory="true" field-type="currency" blank-if-zero="true" autofocus="autofocus"/&gt;
    &lt;/div&gt;

    &lt;div class="field"&gt;
      &lt;label&gt;Payments&lt;/label&gt;
      &lt;input id="numPayments" mandatory="true" field-type="integer" blank-if-zero="true"/&gt;
      &lt;select id="cboPaymentFreq" mandatory="true"&gt;&lt;/select&gt;
    &lt;/div&gt;

    &lt;div class="ui right aligned grid"&gt;
      &lt;div class="sixteen wide column"&gt;
        &lt;button id="cmdApply" class="ui green left labeled icon right floated button" style="display:none"&gt;
          Apply
          &lt;i class="send outline icon"&gt;&lt;/i&gt;
        &lt;/button&gt;
        &lt;button id="cmdCalculate" class="ui blue left labeled icon right floated button"&gt;
          Calculate
          &lt;i class="calculator outline icon"&gt;&lt;/i&gt;
        &lt;/button&gt;
        &lt;button id="cmdReset" class="ui left labeled icon right floated button"&gt;
          Reset
          &lt;i class="undo outline icon"&gt;&lt;/i&gt;
        &lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&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 mClientId = "&lt;%[ClientId]%&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", { style: false });

  // Lists

  // Controls
  $("#cboAccountType").change(cboAccountType_Change);
  $("input,select").change(CalculationClear);

  // Account Types List
  widget.UI.DDListFromCollection("cboAccountType", mAccountTypes, "Description", "AccountTypeId");
  cboAccountType.value = mDefaultAccountTypeId;
  cboAccountType_Change();

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

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

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

  // Show 'Apply' button if signed in as a Client
  if (mClientId) $("#cmdApply").show();
});

// ==============
// 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("cboPaymentFreq", mAccountType.PaymentFreqsList, mAccountType.DefaultPaymentFreq);
  numAmount.value = widget.FormatCurrency(mAccountType.LoanAmount, false, true);
  cboPaymentFreq.value = mAccountType.DefaultPaymentFreq;
  numPayments.value = widget.FormatNumber(mAccountType.DefaultPayments, 0, true, true);
}

// =======================================
// Validate and return a JavaScript object
// =======================================
function Validate() {
  // Create object
  var o = {};
  o.AccountTypeId = cboAccountType.value;
  o.Amount = numAmount.value;
  o.Payments = numPayments.value;
  o.PaymentFreq = cboPaymentFreq.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.Payments) {
    window.alert("Payments not entered.");
    numPayments.focus();
    return;
  }
  else if (!o.PaymentFreq) {
    window.alert("Payment Frequency not entered.");
    cboPaymentFreq.focus();
    return;
  }

  // Return object
  return o;
}

// =========
// Calculate
// =========
function Calculate() {
  // Validate and create object
  var o = Validate();
  if (!o) 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);
}

// =================
// Clear Calculation
// =================
function CalculationClear() {
  divResults.html("");
}

// =====
// Apply
// =====
function Apply() {
  // Validate and create object
  var o = Validate();
  if (!o) return;

  // Confirm
  if (!window.confirm("Submit this Loan Application?\n\nA 'Quote' Loan will be added which will then be reviewed by an Account Manager.")) return;

  // Apply
  widget.GetString("Apply", o, Apply_Done, Apply_Fail);
}

function Apply_Done(data) {
  // Show new 'Quote' Account Id
  window.alert("A new Quote Account '" + data + "' has been created.");

  // Close
  widget.Close();
}

function Apply_Fail(errorMessage) {
  divResults.text(errorMessage);
}

&lt;/script&gt;

&lt;/body&gt;</TemplateText>
    <TemplateTextBookmarks />
    <TimeoutSeconds>60</TimeoutSeconds>
    <UniqueId>5GbydbzIPkSlbh3AOd-W-g</UniqueId>
    <AllowRefresh>true</AllowRefresh>
    <Caption>Client Quote</Caption>
    <HtmlWidgetMaxHeight>0</HtmlWidgetMaxHeight>
    <HtmlWidgetMaxWidth>0</HtmlWidgetMaxWidth>
    <HtmlWidgetNeverApplyStyling>false</HtmlWidgetNeverApplyStyling>
    <HtmlWidgetResourceChartsApex>false</HtmlWidgetResourceChartsApex>
    <HtmlWidgetResourceCssSummaryPage2>true</HtmlWidgetResourceCssSummaryPage2>
    <HtmlWidgetResourceCssWidget>false</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>CC</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>