;;==============================================================================
;; TrustRate.tdl — TallyPrime 2.0+ Integration Plugin
;; Version: 1.0
;;
;; REQUIREMENTS: TallyPrime 2.0 or higher (uses $$HTTPGet / $$HTTPPost)
;;
;; INSTALLATION:
;;   1. Copy this file to your TallyPrime folder (e.g. C:\TallyPrime\)
;;   2. In TallyPrime: F12 > Configure > Advanced Configuration > TDL
;;      Under "Files on Startup" add the full path to TrustRate.tdl
;;   3. Restart TallyPrime
;;   4. Open any Sales Voucher — three new buttons appear in the button bar
;;
;; FIRST RUN:
;;   Press Alt+F9 inside any Voucher to enter your TrustRate API key
;;   (Get your API key from the TrustRate dashboard → API Keys)
;;
;; FLOW:
;;   1. Open a Sales Voucher (invoice)
;;   2. Press Alt+T — enter buyer's mobile number
;;      - If they're already trustRate-verified: shows their trustRate score,
;;        KYC status, overdue history
;;      - If not (new buyer, or not yet Tier-3 verified): TrustRate
;;        automatically sends them a WhatsApp verification link on the spot —
;;        no separate step needed. Check back with Alt+T once they've
;;        completed it.
;;   3. Confirm you want to give credit → enter payment due date
;;   4. Fill in the invoice items as usual
;;   5. Press Alt+G — agreement is created automatically
;;      Buyer receives a notification to confirm
;;
;; KEYBOARD SHORTCUTS (only inside Voucher):
;;   Alt+T  — Check buyer trust score
;;   Alt+G  — Create credit agreement from current invoice
;;   Alt+F9 — Configure API key / Base URL
;;==============================================================================

;;──────────────────────────────────────────────────────────────────────────────
;; PERSISTENT SYSTEM VARIABLES
;; These survive TallyPrime restarts (saved in tally.ini)
;;──────────────────────────────────────────────────────────────────────────────
[System: Variable]
    TR.ApiKey    : String  : ""
    TR.BaseURL   : String  : "https://trustrate.club"
    TR.Mobile    : String  : ""
    TR.DueDate   : String  : ""
    TR.HasCredit : Logical : No


;;==============================================================================
;; FUNCTIONS
;;==============================================================================

;;──────────────────────────────────────────────────────────────────────────────
;; TR.CheckBuyer — Step 1: check trust score and capture credit intent
;;──────────────────────────────────────────────────────────────────────────────
[Function: TR.CheckBuyer]
    Variable : lURL       : String
    Variable : lBody      : String
    Variable : lMobileEsc : String
    Variable : lResponse  : String
    Variable : lStatus    : String
    Variable : lScore     : String
    Variable : lName      : String
    Variable : lKyc       : String
    Variable : lOverdue   : String
    Variable : lMsg       : String

    ;; Require API key before anything else
    010 : IF   : ##TR.ApiKey = ""
    020 : MSGBOX: "TrustRate — Setup Required" : "API key not configured." + @@NewLine + "Press Alt+F9 to enter your API key."
    030 : RETURN
    040 : END IF

    ;; Reset state from any previous run
    050 : SET  : TR.Mobile    : ""
    060 : SET  : TR.DueDate   : ""
    070 : SET  : TR.HasCredit : No

    ;; Show mobile input form — user fills in buyer mobile and presses Enter
    080 : DISPLAY : TR.MobileForm

    ;; If user cancelled (Escape), TR.Mobile stays empty — bail out
    090 : IF   : ##TR.Mobile = ""
    100 : RETURN
    110 : END IF

    ;; ── Call trust check API — POST with a JSON body, not GET with a URL
    ;; param. $$HTTPGet has no way to set custom headers at all, so a
    ;; header-based API key was never actually reachable from this call (the
    ;; original &api_key=... URL param the server never read was the real bug
    ;; here, not a typo). $$HTTPPost's third argument does support headers,
    ;; but the server accepts the key straight from the JSON body too — same
    ;; convention TR.CreateAgreement below already uses — which is simpler
    ;; and keeps the key out of any URL or access log either way.
    ;; Response format: OK|SCORE|NAME|KYC_LABEL|OVERDUE_COUNT
    ;;                  KYC_SENT|NAME|message     (verification link just sent to buyer)
    ;;                  KYC_PENDING|NAME|message  (link already sent recently, not resent)
    ;;                  ERR|message
    120 : SET  : lMobileEsc : $$StringFindAndReplace:##TR.Mobile:"""":"\"""
    130 : SET  : lURL       : ##TR.BaseURL + "/api/tally/trust"
    140 : SET  : lBody      : "{""api_key"":""" + ##TR.ApiKey + """,""mobile"":""" + ##lMobileEsc + """}"
    150 : SET  : lResponse  : $$HTTPPost:##lURL:##lBody:"Content-Type: application/json"

    160 : SET  : lStatus   : $$StringPart:##lResponse:"|":1

    170 : IF   : ##lStatus = "ERR"
    180 : MSGBOX: "TrustRate" : "Error: " + $$StringPart:##lResponse:"|":2
    190 : RETURN
    200 : END IF

    ;; Buyer isn't Tier-3 verified yet — a link was just sent (or recently
    ;; already was) to their WhatsApp automatically, no separate step needed.
    ;; There's no real trust info to show yet, so stop here instead of asking
    ;; "give credit?" with nothing to base it on.
    210 : IF   : ##lStatus = "KYC_SENT" OR ##lStatus = "KYC_PENDING"
    220 :     MSGBOX: "TrustRate" : $$StringPart:##lResponse:"|":3
    230 :     RETURN
    240 : END IF

    ;; Parse fields from the pipe-delimited OK response
    250 : SET  : lScore   : $$StringPart:##lResponse:"|":2
    260 : SET  : lName    : $$StringPart:##lResponse:"|":3
    270 : SET  : lKyc     : $$StringPart:##lResponse:"|":4
    280 : SET  : lOverdue : $$StringPart:##lResponse:"|":5

    ;; ── Show trust info + ask for credit intent ───────────────────────────────
    290 : SET  : lMsg : "Buyer: " + ##lName + @@NewLine + "trustRate: " + ##lScore + " / 1000" + @@NewLine + "KYC: " + ##lKyc + @@NewLine + "Past Overdues: " + ##lOverdue + @@NewLine + @@NewLine + "Give credit to this buyer?"

    300 : IF   : NOT $$MsgBox:"TrustRate — Give Credit?":##lMsg
    310 : RETURN
    320 : END IF

    ;; ── Ask for due date ──────────────────────────────────────────────────────
    330 : DISPLAY : TR.DueDateForm

    340 : IF   : ##TR.DueDate = ""
    350 : RETURN
    360 : END IF

    370 : SET  : TR.HasCredit : Yes

    380 : MSGBOX: "TrustRate" : "Credit intent saved." + @@NewLine + "Buyer: " + ##lName + @@NewLine + "Due: " + ##TR.DueDate + @@NewLine + @@NewLine + "Now fill in the invoice. When done, press Alt+G to create the agreement."


;;──────────────────────────────────────────────────────────────────────────────
;; TR.CreateAgreement — Step 2: create agreement from current invoice data
;;──────────────────────────────────────────────────────────────────────────────
[Function: TR.CreateAgreement]
    Variable : lPartyName : String
    Variable : lAmount    : String
    Variable : lVoucherNo : String
    Variable : lURL       : String
    Variable : lBody      : String
    Variable : lResponse  : String
    Variable : lStatus    : String

    ;; Must have run TR.CheckBuyer first
    010 : IF   : NOT ##TR.HasCredit
    020 : MSGBOX: "TrustRate" : "No credit intent found." + @@NewLine + "Press Alt+T first to check the buyer's trust score."
    030 : RETURN
    040 : END IF

    ;; Read data from the current voucher being edited
    050 : SET  : lPartyName : $PartyLedgerName
    060 : SET  : lAmount    : $$String:$$Abs:$Amount
    070 : SET  : lVoucherNo : $VoucherNumber

    080 : IF   : ##lPartyName = ""
    090 : MSGBOX: "TrustRate" : "Party name is empty. Please select the buyer ledger first."
    100 : RETURN
    110 : END IF

    120 : IF   : ##lAmount = "0" OR ##lAmount = ""
    130 : MSGBOX: "TrustRate" : "Invoice amount is zero. Please add items to the invoice first."
    140 : RETURN
    150 : END IF

    ;; ── Escape JSON-unsafe characters before interpolating free-text ledger
    ;; data into the request body below. A ledger/voucher name containing a
    ;; literal " or \ would otherwise break the hand-built JSON string.
    ;; Backslash MUST be escaped before quotes, or the backslashes inserted
    ;; for quote-escaping would themselves get doubled on a second pass.
    160 : SET  : lPartyName : $$StringFindAndReplace:##lPartyName:"\":"\\"
    170 : SET  : lPartyName : $$StringFindAndReplace:##lPartyName:"""":"\"""
    180 : SET  : lVoucherNo : $$StringFindAndReplace:##lVoucherNo:"\":"\\"
    190 : SET  : lVoucherNo : $$StringFindAndReplace:##lVoucherNo:"""":"\"""

    ;; ── POST to /api/tally/agreement ──────────────────────────────────────────
    ;; JSON with api_key in body — no custom headers needed in TDL
    200 : SET  : lURL  : ##TR.BaseURL + "/api/tally/agreement"
    210 : SET  : lBody : "{""api_key"":""" + ##TR.ApiKey + """,""credit_type"":""goods"",""counterparty_mobile"":""" + ##TR.Mobile + """,""counterparty_name"":""" + ##lPartyName + """,""amount"":" + ##lAmount + ",""due_date"":""" + ##TR.DueDate + """,""invoice_reference"":""" + ##lVoucherNo + """}"

    220 : SET  : lResponse : $$HTTPPost:##lURL:##lBody:"Content-Type: application/json"

    230 : SET  : lStatus : $$StringPart:##lResponse:"|":1

    240 : IF   : ##lStatus = "OK"
    250 :     SET  : TR.HasCredit : No
    260 :     SET  : TR.Mobile    : ""
    270 :     SET  : TR.DueDate   : ""
    280 :     MSGBOX: "TrustRate" : "Agreement created!" + @@NewLine + "ID: " + $$StringPart:##lResponse:"|":2 + @@NewLine + ##lPartyName + " will receive a notification to confirm."
    290 : ELSE
    300 :     MSGBOX: "TrustRate" : "Failed to create agreement." + @@NewLine + $$StringPart:##lResponse:"|":2
    310 : END IF


;;──────────────────────────────────────────────────────────────────────────────
;; TR.OpenSetup — configure API key and base URL
;;──────────────────────────────────────────────────────────────────────────────
[Function: TR.OpenSetup]
    010 : DISPLAY : TR.SetupForm


;;==============================================================================
;; FORMS
;;==============================================================================

;;──────────────────────────────────────────────────────────────────────────────
;; Mobile number input form
;;──────────────────────────────────────────────────────────────────────────────
[Form: TR.MobileForm]
    Width     : 55
    Height    : 9
    Space Top : 2
    Part      : TR.MobileFormPart
    Button    : TR.MobileOKBtn
    Button    : TR.MobileCancelBtn

[Part: TR.MobileFormPart]
    Line : TR.MobileLblLine
    Line : TR.MobileInputLine
    Scroll: No

[Line: TR.MobileLblLine]
    Field : TR.MobileLabelFld

[Field: TR.MobileLabelFld]
    Use       : Name Field
    Info      : "Enter buyer's 10-digit mobile number:"
    Width     : 40 Indent
    Skip      : Yes

[Line: TR.MobileInputLine]
    Field : TR.MobileInputFld

[Field: TR.MobileInputFld]
    Use        : Short Name Field
    Width      : 20 Indent
    Set Always : TR.Mobile : $Value

[Button: TR.MobileOKBtn]
    Key    : Enter
    Title  : "Check Score"
    Action : Form Accept

[Button: TR.MobileCancelBtn]
    Key    : Escape
    Title  : "Cancel"
    Action : Form Reject


;;──────────────────────────────────────────────────────────────────────────────
;; Due date input form
;;──────────────────────────────────────────────────────────────────────────────
[Form: TR.DueDateForm]
    Width     : 55
    Height    : 9
    Space Top : 2
    Part      : TR.DueDateFormPart
    Button    : TR.DueDateOKBtn
    Button    : TR.DueDateCancelBtn

[Part: TR.DueDateFormPart]
    Line : TR.DueDateLblLine
    Line : TR.DueDateInputLine
    Scroll: No

[Line: TR.DueDateLblLine]
    Field : TR.DueDateLabelFld

[Field: TR.DueDateLabelFld]
    Use       : Name Field
    Info      : "Payment due date (when buyer must pay):"
    Width     : 40 Indent
    Skip      : Yes

[Line: TR.DueDateInputLine]
    Field : TR.DueDateInputFld

[Field: TR.DueDateInputFld]
    Use        : Date Field
    Width      : 20 Indent
    ;; Store date as YYYY-MM-DD string for our API
    Set Always : TR.DueDate : $$DateToStr:$Value:"YYYY-MM-DD"

[Button: TR.DueDateOKBtn]
    Key    : Enter
    Title  : "Confirm"
    Action : Form Accept

[Button: TR.DueDateCancelBtn]
    Key    : Escape
    Title  : "Cancel"
    Action : Form Reject


;;──────────────────────────────────────────────────────────────────────────────
;; Setup form — API key and base URL
;;──────────────────────────────────────────────────────────────────────────────
[Form: TR.SetupForm]
    Width     : 70
    Height    : 12
    Space Top : 2
    Part      : TR.SetupFormPart
    Button    : TR.SetupOKBtn
    Button    : TR.SetupCancelBtn

[Part: TR.SetupFormPart]
    Line : TR.SetupLbl1Line
    Line : TR.SetupApiKeyLine
    Line : TR.SetupLbl2Line
    Line : TR.SetupURLLine
    Scroll: No

[Line: TR.SetupLbl1Line]
    Field : TR.SetupLbl1Fld

[Field: TR.SetupLbl1Fld]
    Use   : Name Field
    Info  : "API Key  (from TrustRate Dashboard → API Keys):"
    Width : 50 Indent
    Skip  : Yes

[Line: TR.SetupApiKeyLine]
    Field : TR.SetupApiKeyFld

[Field: TR.SetupApiKeyFld]
    Use        : Long Name Field
    Width      : 60 Indent
    Set Always : TR.ApiKey : $Value

[Line: TR.SetupLbl2Line]
    Field : TR.SetupLbl2Fld

[Field: TR.SetupLbl2Fld]
    Use   : Name Field
    Info  : "Base URL (your deployed app URL, no trailing slash):"
    Width : 60 Indent
    Skip  : Yes

[Line: TR.SetupURLLine]
    Field : TR.SetupURLFld

[Field: TR.SetupURLFld]
    Use        : Long Name Field
    Width      : 60 Indent
    Set Always : TR.BaseURL : $Value

[Button: TR.SetupOKBtn]
    Key    : Enter
    Title  : "Save Settings"
    Action : Form Accept

[Button: TR.SetupCancelBtn]
    Key    : Escape
    Title  : "Cancel"
    Action : Form Reject


;;==============================================================================
;; HOOK BUTTONS INTO VOUCHER ENTRY FORM
;; Adds three buttons to all voucher types (Sales, Purchase, etc.)
;;==============================================================================
[#Form: Voucher]
    Add : Button : TR.CheckBuyerBtn
    Add : Button : TR.CreateAgreementBtn
    Add : Button : TR.SetupBtn

[Button: TR.CheckBuyerBtn]
    Key    : Alt + T
    Title  : "TrustRate (Alt+T)"
    Action : Call : TR.CheckBuyer

[Button: TR.CreateAgreementBtn]
    Key    : Alt + G
    Title  : "Create Agreement (Alt+G)"
    Action : Call : TR.CreateAgreement

[Button: TR.SetupBtn]
    Key    : Alt + F9
    Title  : "TrustRate Setup (Alt+F9)"
    Action : Call : TR.OpenSetup
