<%@ language = "JavaScript" %>
<% /*
    $Revision$
    $Id$

    File:           base27.asp

    Description:    Conversie van xml naar json voor Base27 koppeling
    Parameters:
    Context:

    Notes:          Informatie m.b.t. Base27 API : https://base27.eu/doc/rest
*/
var JSON_Result = true;
ANONYMOUS_Allowed = 1;
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/save2db.inc" -->
<!-- #include file="../Shared/xml_converter.inc" -->
<%
    var ll = getQParamInt("logging", 0);
    if (ll > 0)
        __Logging = ll; // Voor de rest van dit bestand

    var debug = 0;

    function callAPI(actie, params)
    {
        obj_log( {"callAPI()": { "actie": actie, "params": params}} );
        var api_conn = { actie: ""};

        switch (actie) // Gebruik hier de parameters uit de aanroep.
        {              // Maak het api_conn object waarin alle gegevens staan om de actie uit te kunnen voeren.
            case "login":           ext_url = "/oauth/token";
                                    api_conn = { actie: "login"
                                               , url: params.config.base_url + ext_url
                                                            + "?grant_type=password"
                                                            + "&username=" + params.config.url_username
                                                            + "&password=" + encodeURIComponent(params.config.url_password)
                                               , aut_un: params.config.aut_username
                                               , aut_pw: params.config.aut_password
                                               , aut_token: getBase64("Basic ", params.config.aut_username + ":" + params.config.aut_password)
                                               , methode: "POST"
                                               , contenttype: "application/json;charset=UTF-8"
                                               };
                                    break;
            case "incident":        ext_url = "/entities/base$Incident";
                                    api_conn = { actie: "incident"
                                               , url: params.config.base_url + ext_url
                                               , bearer: params.info.bearer_token
                                               , methode: "POST"
                                               , contenttype: "application/json"
                                               , data: {}
                                               };
                                    break;
            case "comment":         ext_url = "/entities/base$Comment";
                                    api_conn = { actie: "comment"
                                               , url: params.config.base_url + ext_url
                                               , bearer: params.info.bearer_token
                                               , methode: "POST"
                                               , contenttype: "application/json"
                                               , data: {}
                                               };
                                    break;
            case "incidentGET":     ext_url = "/entities"
                                    api_conn = { actie: "incidentGET"
                                               , url: params.config.base_url
                                                            + ext_url
                                                            + "/" + params.data._entityName
                                                            + "/" + params.data.id
                                                            + "?returnNulls=true&dynamicAttributes=true"
                                               , bearer: params.info.bearer_token
                                               , methode: "GET"
                                               , contenttype: "application/json"
                                               };
                                    break;

            case "fileupload":      // upload file
                                    api_url = "/rest/v2/files"
                                    api_conn.methode = "POST";
                                    break;
            case "filelink":        // link uploaded file to incident
                                    api_url = "/rest/v2/entities/base$File"
                                    api_conn.methode="POST";
                                    break;
            case "link":            // add link to incident
                                    api_url = "/rest/v2/entities/base$File"
                                    api_conn.methode = "POST";
                                    break;
        }

        api_conn_log(api_conn, params);
        var api_result = { status: -1
                         , message: ""
                         , data: {}
                         };

        if (api_conn.methode != "")
        {
            try
            {
                var SXH_PROXY_SET_PROXY = 2;
                var http_request = Server.CreateObject("WinHTTP.WinHTTPRequest.5.1");
                if (params.config.proxy && params.config.proxy != "")
                {
                    http_request.SetProxy(SXH_PROXY_SET_PROXY, params.config.proxy);
                }
                http_request.Open(api_conn.methode, api_conn.url, false); // Synchroon

                switch (actie)
                {
                    case "login":       http_request.setRequestHeader("Authorization", api_conn.aut_token);
                                        http_request.setRequestHeader("Content-Type", api_conn.contenttype);
                                        http_request.Send();
                                        status = http_request.status;
                                        break;
                    case "incident":
                    case "comment":     http_request.setRequestHeader("Authorization", "Bearer " + api_conn.bearer);
                                        http_request.setRequestHeader("Accept", "*/*");
                                        http_request.setRequestHeader("Content-Type", api_conn.contenttype);
                                        http_request.send(JSON.stringify(params.data));
                                        break;
                    case "incidentGET": http_request.setRequestHeader("Authorization", "Bearer " + api_conn.bearer);
                                        http_request.setRequestHeader("Accept", "*/*");
                                        http_request.setRequestHeader("Content-Type", api_conn.contenttype);
                                        http_request.send();
                                        break;
                }

                api_result = request_result(http_request); // Wat geeft de api-call terug?
            }
            catch (e)
            {
                api_result.message = "Base27 connection error: " + e.description;
            }
        }
        else
        {
            api_result.message = (api_conn.missing_id ? "unknown id in " : "No method found for executing ") + api_conn.baseurl + api_conn.url;
        }

        return api_result;
    }


    function getBase64(prefix, str)
    {
        var oCrypto = new ActiveXObject("SLNKDWF.Crypto");
        var base64Code = prefix + oCrypto.base64(str);
        __Log({"function getBase64": {"prefix": prefix, "string": str, "result": base64Code}});
        return base64Code;
    }

    function obj_log(obj)
    {
        if (__Logging > 0)
            __Log(obj);
    }

    function api_conn_log(conn_param, params)
    {
        obj_log( {"api_conn": conn_param} );
        obj_log( {"body data:": params.data} );
    }

    function request_result(p_request)
    {
        var result = {status: p_request.status};
        var status_ok = [200,201,204,206];
        if (inArray(result.status, status_ok))
        {
            result.success = true;
            result.message = "";
            result.data = ( p_request.responseText
                          ? JSON.parse( p_request.responseText)
                          : {}
                          );
        }
        else 
        {
            result.success = false;
            result.message = "Base27 error. Status: " + p_request.status;
            result.data = {};
        }
        obj_log( {"RequestResult": result});
        return result;
    }

    function load_headerdata()
    {
        function xml_from_file()
        {   // Te gebruiken bij testen als je al een xml-bestand met data hebt.
            if (debug == 1)
            {
              var test_header_xml_file = "../../temp/pzee/putorders/puo_20250811-120141_01_transformed.xml";
            }
            var fso = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = Server.MapPath(test_header_xml_file);
            var f = fso.OpenTextFile(filePath, 1);
            var x = f.ReadAll();
            f.Close();
            return x.substr(3);
        }

        function set_customFields(obj)
        {   // Vervang de namen van de custom velden. Xml-tagnames moeten met een underscore of letter beginnen, dus niet met +.
            var data = obj.facilitor.base27.data;
            data["+reporterName"] = data._reporterName;
            data["+reporterEmail"] = data._reporterEmail;
            data["+location"] = data._location;
            data["+personalData"] = data._personalData;
            data["+personalDataDescription"] = data._personalDataDescription;
            delete data._reporterName;
            delete data._reporterEmail;
            delete data._location;
            delete data._personalData;
            delete data._personalDataDescription;

            obj.facilitor.base27.data = data;
            return obj;
        }

        // Lees de xml-data uit de html-header.
        var xmlReq = Server.CreateObject("MSXML2.DOMDocument.6.0");

        if (debug == 1)
        {
            xmlReq.loadXML(xml_from_file());  // testen met een vast bestand
        }
        else
        {
            xmlReq.load(Request);             // xml uit data header van base27.asp halen
        }

        // Converteer de xml naar json-dataobject.
        var objreq = xmlToJson(xmlReq);
        objreq = set_customFields(objreq);
        var result_header = { success: (objreq && objreq.facilitor && objreq.facilitor.base27 ? true : false)
                            , facilitor: objreq.facilitor
                            };
        obj_log( {"load_headerdata": result_header} );
        return result_header;
    }

    function load_config(config_file)
    {
        var result_config = { success: false
                            , message: ""
                            , config: {}
                            };
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filePath = Server.MapPath("../../CUST/" + config_file);
        if (fso.FileExists(filePath))
        {
            /*
            in een config bestand is het fijn als je ook commentaar kunt toevoegen
            Het verwijderen ervan kan niet met regexp alleen omdat je te maken hebt met eventueel commentaartekens binnen een tekststring, bv in een url
            Daarvoor moet een functie gemaakt worden.
            */
            var f = fso.OpenTextFile(filePath, 1);
            result_config.config = JSON.parse(f.ReadAll());
            result_config.success = true;
            f.Close();
        }
        else
        {
            result_config.message = "Configuratie bestand niet aanwezig: " + filePath;
        }

        obj_log( {"load_config": result_config} );
        return result_config;
    }



    // *************************************************************************
    __Log("*> Base27.api");
    var header_data = load_headerdata();
    var instellingen = load_config(header_data.facilitor.base27.configfile);

    if (header_data.success && instellingen.success)
    {
        var obj_base27 = header_data.facilitor.base27 || {};
        obj_base27.config = instellingen.config;

        var api_result = callAPI("login", obj_base27);
        if (api_result.success)
        {   // Nu kan de werkelijke actie worden gedaan.
            obj_base27.info.bearer_token = api_result.data.access_token;
            var api_result = callAPI(obj_base27.info.actie, obj_base27);
            if (api_result.success)
            {
                if (obj_base27.info.actie == "incident")
                {
                    if (api_result.status == 201)
                    {
                        if (header_data.facilitor.melding.opdracht)
                        {
                            var opdr_key = header_data.facilitor.melding.opdracht.mld_opdr_key;
                            var sql = "UPDATE mld_opdr"
                                    + "   SET mld_opdr_externnr = " + safe.quoted_sql(String(api_result.data.id))
                                    + " WHERE mld_opdr_key = " + opdr_key;
                            var err = Oracle.Execute(sql, true);
                            var result = { ticket: { status:  (err.fullMsg ? 600 : 200)
                                                   , message: (err.fullMsg ? err.friendlyMsg : "opdracht {0} succesvol verstuurd".format(opdr_key))
                                                   }};
                        }
                        else
                        {
                            var mld_key = header_data.facilitor.melding.mld_melding_key;
                            var sql = "UPDATE mld_melding"
                                    + "   SET mld_melding_externnr = " + safe.quoted_sql(String(api_result.data.id))
                                    + " WHERE mld_melding_key = " + mld_key;
                            var err = Oracle.Execute(sql, true);
                            var result = { ticket: { status:  (err.fullMsg ? 600 : 200)
                                                   , message: (err.fullMsg ? err.friendlyMsg : "melding {0} succesvol verstuurd".format(mld_key))
                                                   }};
                        }
                    }
                }
                else if (obj_base27.info.actie == "comment")
                {
                    if (header_data.facilitor.melding.opdracht)
                    {
                        var opdr_key = header_data.facilitor.melding.opdracht.mld_opdr_key;
                        var result = { ticket: { status: 200
                                               , message: "Notitie bij opdracht {0} succesvol toegevoegd".format(opdr_key)
                                               }};
                    }
                    else
                    {
                        var mld_key = header_data.facilitor.melding.mld_melding_key;
                        var result = { ticket: { status: 200
                                               , message: "Notitie bij melding {0} succesvol toegevoegd".format(mld_key)
                                               }};
                    }
                }
            }
            else
            {
                var result = { ticket: { status: api_result.status
                                       , message: "actie '{0}' mislukt: {1}".format(obj_base27.info.actie, api_result.error +";"+api_result.details)
                                       }};
            }
        }
        else
        {
            var result = { ticket: { status: api_result.status
                                   , message: "aanmelden bij Base27 niet gelukt. " + api_result.message  
                                   }};
        }
    }
    else
    {
        var result = { ticket: { status: 600
                               , message: "geen base27 data aanwezig"
                               }};
        __DoLog(safe.html(result.ticket.message), "ff0000");
    }

    __Log( {"Resultaat_Base27": result} );
    __Log("*< Base27.api");
    Response.Write(JSON.stringify(result));
    //Response.End;
%>
<% ASPPAGE_END(); %>


